martedì 2 novembre 2010

Problem 10

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

Find the sum of all the primes below two million.

solution = sum $ takeWhile (<2000000) primes
    
primes :: Integral a => [a]
primes = 2 : iterate nextPrime 3
    where nextPrime x = head $ filter isPrime[(x+1)..] 

isPrime :: Integral a => a -> Bool
isPrime x = and $ [mod x p /= 0 | p <- takeWhile lowerThanSqrtX primes]
    where lowerThanSqrtX candidate = candidate <= (round $ sqrt $ fromIntegral x)

Nessun commento:

Posta un commento