Project Euler #10

Wednesday July 30thFunctional Programming, Haskell, Project Euler Category

WARNING! This post contains a spoiler for Problem #10 listed at Project Euler. Do not read the rest of this post if you’re planning to attempt to solve the problem yourself.

Problem #10 takes us back into the realm of the relatively boring - prime numbers (again). The question is as follows:

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Exciting stuff! Since we’ve already got ourselves a relatively nifty prime number generator from a previous post, we can simply reuse this, along with the sum function that comes in Prelude, to generate the answer.

Here is what the code looks like:

merge :: (Ord a) => [a] -> [a] -> [a]
merge xs@(x:xt) ys@(y:yt) = 
  case compare x y of
    LT -> x : (merge xt ys)
    EQ -> x : (merge xt yt)
    GT -> y : (merge xs yt)
 
diff :: (Ord a) => [a] -> [a] -> [a]
diff xs@(x:xt) ys@(y:yt) = 
  case compare x y of
    LT -> x : (diff xt ys)
    EQ -> diff xt yt
    GT -> diff xs yt
 
primes, nonprimes :: [Integer]
primes    = [2, 3, 5] ++ (diff [7, 9 ..] nonprimes) 
nonprimes = foldr1 f $ map g $ tail primes
  where 
    f (x:xt) ys = x : (merge xt ys)
    g p         = [ n * p | n <- [p, p + 2 ..]]
 
main :: IO ()
main = print $ sum (takeWhile (<2000000) primes)

I don’t really have much else to say about this. I won’t bother with the performance information because it’s not really doing anything too exciting that hasn’t already been discussed.

Cheers!

3 Comments

  1. gav
    July 30, 2008

    Unless i’m mistaken “main = print $ sum (takeWhile (<1000000) primes)” iterates over the primes below one million but the question asks for below two million, or am I just being picky! :-)

  2. OJ
    July 31, 2008

    You are indeed correct my friend! It looks like they have changed the problem since I solved it the first time (I did this quite a while ago, just haven’t got round to posting it). Thanks for noticing, I’ll fix that up no :) Cheers!

  3. gav
    July 31, 2008

    Not a problem. It was probably the only bit of that code I properly understood!

Leave a comment

Size

Colors