Excluding the calculated results from the map [1 ..]?

I am currently working on a program that calculates friendly pairs (Project Euler Problem 21 ). I already found a solution, but I noticed that the drawback in my program was that it evaluates all the numbers in the set [1 ..] regardless of whether we have already established that the number is a pair.

i.e. If at present the pair is considered to be the rating 220 and 284, however, continuing to work when the card function reaches 284, it should not evaluate it again.

import Data.List

properDivisors :: (Integral a) => a -> [a]
properDivisors n = [x | x <- [1..n `div` 2],
                        n `mod` x == 0 ]

amicablePairOf :: (Integral a) => a -> Maybe a
amicablePairOf a
    | a == b = Nothing
    | a == dOf b = Just b
    | otherwise = Nothing
        where dOf x = sum (properDivisors x)
              b = dOf a

getAmicablePair :: (Integral a) => a -> [a]
getAmicablePair a = case amicablePairOf a of
            Just b -> [a,b]
            Nothing -> []


amicables = foldr (++) [] ams
    where ams = map getAmicablePair [1..]

As an example:

take 4 amicables

returns:

[220,284,284,220]

I am new to Haskell and functional programming, so forgive me if this is an obvious solution.

+3
source share
2 answers

, , . , , , , . :

import Data.List

divSum :: (Integral a) => a -> [a]
divSum n = sum (filter (\a -> a `mod` n == 0) [1..n `div` 2])

isAmicable :: (Integral a) => a -> Bool
isAmicable a = a /= b && a == c where
  b = divSum a
  c = divSum b

amicables = filter isAmicable [1..]
+5

, getAmicablePair ?

getAmicablePair :: (Integral a) => a -> [a]
getAmicablePair a = case amicablePairOf a of
            Just b -> if a < b then [a,b] else []
            Nothing -> []

...

+2

All Articles