Vinicius Teshima 5 месяцев назад
Родитель
Сommit
b20e52b81f
1 измененных файлов с 35 добавлено и 0 удалено
  1. 35 0
      haskell/src/0003.hs

+ 35 - 0
haskell/src/0003.hs

@@ -0,0 +1,35 @@
+{-
+The prime factors of 13195 are 5, 7, 13 and 29.
+What is the largest prime factor of the number 600851475143?
+-}
+
+import Debug.Trace
+
+is_prime :: Int -> Bool
+is_prime x = go' x 2
+  where
+    go' 0 y = True
+    go' 1 y = True
+    go' x 2 = case (mod x 2) of
+                0 -> False
+                _ -> go' x 3
+    go' x y
+      | x == y    = True
+      | otherwise = case (mod x y) of
+                      0 -> False
+                      _ -> go' x (y + 2)
+
+solution :: Int
+solution = go' 1 0 where
+  target = 600851475143
+  go' x y
+    | x == target = y
+    | otherwise   = case (mod target x) of
+                      0 -> case (is_prime x) of
+                             True  -> go' (x + 2) x
+                             False -> go' (x + 2) y
+                      _ -> go' (x + 2) y
+
+-- This takes about 1hr to end
+main :: IO ()
+main = putStrLn ("Solution: " ++ show solution)