Browse Source

[Haskell][21] Adding Solution

Vinicius Teshima 4 months ago
parent
commit
41064af553
2 changed files with 38 additions and 0 deletions
  1. 26 0
      haskell/src/0021.hs
  2. 12 0
      haskell/src/Utils.hs

+ 26 - 0
haskell/src/0021.hs

@@ -0,0 +1,26 @@
+{-
+Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
+If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.
+For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
+Evaluate the sum of all the amicable numbers under 10000.
+-}
+
+import Utils
+
+import Data.List
+import Data.Maybe
+
+amicableNum :: Int -> Maybe (Int, Int)
+amicableNum a = if (a == na && a /= b)
+                then Just (a, b)
+                else Nothing
+                  where b = sum (divs a)
+                        na = sum (divs b)
+
+solution :: Int
+solution = foldl (\c x -> c+x) 0 abs
+  where
+    abs = nub (takeWhile (<10000) (flattenTupleList (catMaybes (map amicableNum (iterate (+1) 1)))))
+
+main :: IO ()
+main = putStrLn ("Solution: " ++ show solution)

+ 12 - 0
haskell/src/Utils.hs

@@ -205,3 +205,15 @@ module Utils where
   factorial 0 = 0
   factorial 1 = 1
   factorial x = x * factorial (x-1)
+
+  divs :: Int -> [Int]
+  divs 0 = []
+  divs 1 = [1]
+  divs 2 = [1, 2]
+  divs x = filter (\x' -> (mod x x') == 0) (take (x-1) (iterate (+1) 1))
+
+  flattenTupleList :: [(a, a)] -> [a]
+  flattenTupleList [] = []
+  flattenTupleList [(x, y)] = [x, y]
+  flattenTupleList ((x, y):xs) = [x, y] ++ (flattenTupleList xs)
+