Skip to content

Instantly share code, notes, and snippets.

@SeijiEmery
Last active August 29, 2015 14:08
Show Gist options
  • Save SeijiEmery/6f9bdda646bd922e649f to your computer and use it in GitHub Desktop.
Save SeijiEmery/6f9bdda646bd922e649f to your computer and use it in GitHub Desktop.
Project Euler Problems 1-3
-- Note: fib_inf generates an infinite list
fib_inf :: Int -> Int -> [Int]
fib_inf a b = a : fib_inf b (a+b)
-- Which is ok, since Haskell uses lazy evaluation
fib_to n = takeWhile (< n) (fib_inf 0 1)
is_even x = x `mod` 2 == 0
even_fib_sum = sum . (filter is_even) . fib_to
-- Boilerplate to print our result
main :: IO ()
main = do
print (even_fib_sum 4000000)
-- Note: need to have the primes package installed (didn't want to write my own primes implementation xD)
import Data.Numbers.Primes
largest_prime_factor :: Int -> Int
largest_prime_factor n = lpf n 1 primes
where lpf x m (p:ps)
| x < p = m
| x >= p = case x `mod` p of
0 -> lpf (x `quot` p) p ps
otherwise -> lpf x m ps
main :: IO ()
main = do
print (largest_prime_factor 600851475143)
sum_mult_35_below n = sum . (filter divby_3_or_5) $ [ 1 .. n ]
where divby_3_or_5 x = (x `mod` 3 == 0) || (x `mod` 5 == 0)
main :: IO ()
main = do
print (sum_mult_35_below 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment