Add Haskell solutions for Problems 1, 2, 3

This commit is contained in:
daniele 2024-03-29 11:50:11 +01:00
parent 48503b8e27
commit aad8467fb9
Signed by: fuxino
GPG Key ID: 981A2B2A3BBF5514
3 changed files with 53 additions and 0 deletions

12
Haskell/p001.hs Normal file
View File

@ -0,0 +1,12 @@
-- If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
--
-- Find the sum of all the multiples of 3 or 5 below 1000.
sumMultiples :: (Integral n) => n
sumMultiples = sum(filter p [ n | n <- [1..999] ])
where p n = n `mod` 3 == 0 || n `mod` 5 == 0
main :: IO ()
main = do
let result = sumMultiples
putStrLn $ "Project Euler, Problem 1\n"
++ "Answer: " ++ (show result)

18
Haskell/p002.hs Normal file
View File

@ -0,0 +1,18 @@
-- Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
--
-- 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
--
-- By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
fib :: (Integral n) => n -> n
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib(n-2)
sumEvenFib :: (Integral n) => n
sumEvenFib = sum $ filter even $ takeWhile (<=4000000) (map fib [0..])
main :: IO ()
main = do
let result = sumEvenFib
putStrLn $ "Project Euler, Problem 2\n"
++ "Answer: " ++ (show result)

23
Haskell/p003.hs Normal file
View File

@ -0,0 +1,23 @@
-- The prime factors of 13195 are 5, 7, 13 and 29. --
-- What is the largest prime factor of the number 600851475143?
isPrime :: (Integral n) => n -> Bool
isPrime 1 = False
isPrime 2 = True
isPrime 3 = True
isPrime n =
n `mod` 2 /= 0 && n `mod` 3 /= 0 && null [ x | x <- candidates, n `mod` x == 0 || n `mod` (x+2) == 0 ]
where candidates = [5,11..limit]
limit = floor(sqrt(fromIntegral n)) + 1
maxPrimeFactor :: (Integral n) => n -> n
maxPrimeFactor n
| isPrime n = n
| n `mod` 2 == 0 = maxPrimeFactor $ fromIntegral n `div` 2
| otherwise = maxPrimeFactor $ fromIntegral n `div` head [i | i <- [3,5..], n `mod` i == 0 && isPrime i]
main :: IO ()
main = do
let result = maxPrimeFactor 600851475143
putStrLn $ "Project Euler, Problem 3\n"
++ "Answer: " ++ (show result)