0023.hs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. {-
  2. A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
  3. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
  4. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
  5. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
  6. -}
  7. import Utils
  8. import Data.List
  9. --import Data.Map (Map)
  10. --import qualified Data.Map as Map
  11. import Data.IntSet (IntSet)
  12. import qualified Data.IntSet as IntSet
  13. import Debug.Trace
  14. isAbundant :: Int -> Bool
  15. isAbundant x = (divs x |> sum) > x
  16. abundants :: [Int]
  17. abundants = iterate (+1) 1 |> take 28124 |> filter isAbundant
  18. abundantsSet :: IntSet
  19. abundantsSet = IntSet.fromList abundants
  20. f :: Int -> Bool
  21. f n = go' abundants
  22. where
  23. go' [] = False
  24. go' [x] = IntSet.member (n-x) abundantsSet
  25. go' (x:xs)
  26. | x >= n = False
  27. | IntSet.member (n-x) abundantsSet = True
  28. | otherwise = go' xs
  29. solution :: Int
  30. solution = iterate (+1) 1 |> take 28123 |> filter (\x -> (f x) == False) |> sum
  31. main :: IO ()
  32. main = putStrLn ("Solution: " ++ show solution)