Skip to content

Instantly share code, notes, and snippets.

@eakray
Last active July 8, 2022 05:37
Show Gist options
  • Select an option

  • Save eakray/e1d818ace771398cd0c38e59083599bd to your computer and use it in GitHub Desktop.

Select an option

Save eakray/e1d818ace771398cd0c38e59083599bd to your computer and use it in GitHub Desktop.
Project Euler problems
--Problem 1
{-
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.
-}
sumMults :: Integral a => a -> a
sumMults n = sum $ filter (\x -> mod x 3 == 0 || mod x 5 == 0) [1..(n-1)]
sumMults2 n = sum [x | x <- [1..(n-1)], (\x -> mod x 3 == 0 || mod x 5 == 0) x]
--Problem 2
{-
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.
-}
fibs :: Num b => [b]
fibs = map fst $ iterate (\(a,b) -> (b,a+b)) (0,1)
fibSum :: Integral a => a -> a
fibSum n = sum $ filter even $ takeWhile (< n) fibs
--Problem 3
{-
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
-}
primeFactors :: Integral a => a -> [a]
primeFactors n =
case factors of
[] -> [n]
_ -> factors ++ primeFactors (n `div` (head factors))
where factors = take 1 $ filter (\x -> (n `mod` x) == 0) [2 .. n-1]
largestPF :: Integral a => a -> a
largestPF n = head $ reverse $ primeFactors n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment