Improve Haskell solution for Problem 10 using prime sieve
This commit is contained in:
parent
e31b25846c
commit
de4106efe7
@ -1,5 +1,6 @@
|
|||||||
module ProjectEuler
|
module ProjectEuler
|
||||||
( isPrime
|
( isPrime
|
||||||
|
, primeSieve
|
||||||
, lcmm
|
, lcmm
|
||||||
, digitSum
|
, digitSum
|
||||||
, sumProperDivisors
|
, sumProperDivisors
|
||||||
@ -9,6 +10,7 @@ module ProjectEuler
|
|||||||
|
|
||||||
import Data.Char (digitToInt)
|
import Data.Char (digitToInt)
|
||||||
import Data.List (nub)
|
import Data.List (nub)
|
||||||
|
import Data.List.Ordered (minus, unionAll)
|
||||||
|
|
||||||
isPrime :: (Integral n) => n -> Bool
|
isPrime :: (Integral n) => n -> Bool
|
||||||
isPrime 1 = False
|
isPrime 1 = False
|
||||||
@ -19,6 +21,9 @@ isPrime n =
|
|||||||
where candidates = [5,11..limit]
|
where candidates = [5,11..limit]
|
||||||
limit = floor(sqrt(fromIntegral n)) + 1
|
limit = floor(sqrt(fromIntegral n)) + 1
|
||||||
|
|
||||||
|
primeSieve :: (Integral n) => [n]
|
||||||
|
primeSieve = 2:3:[5,7..] `minus` unionAll [[p*p, p*p+2*p..] | p <- tail primeSieve]
|
||||||
|
|
||||||
lcmm :: (Integral n) => [n] -> n
|
lcmm :: (Integral n) => [n] -> n
|
||||||
lcmm values
|
lcmm values
|
||||||
| length values == 2 = lcm (head values) (last values)
|
| length values == 2 = lcm (head values) (last values)
|
||||||
|
@ -2,12 +2,9 @@
|
|||||||
--
|
--
|
||||||
-- Find the sum of all the primes below two million.
|
-- Find the sum of all the primes below two million.
|
||||||
|
|
||||||
import ProjectEuler (isPrime)
|
import ProjectEuler (primeSieve)
|
||||||
|
|
||||||
sumPrimes :: Int -> Int
|
|
||||||
sumPrimes n = sum [ x | x <- [1..n], isPrime x ]
|
|
||||||
|
|
||||||
main = do
|
main = do
|
||||||
let result = sumPrimes 2000000
|
let result = sum $ takeWhile (<2000000) primeSieve
|
||||||
putStrLn $ "Project Euler, Problem 10\n"
|
putStrLn $ "Project Euler, Problem 10\n"
|
||||||
++ "Answer: " ++ show result
|
++ "Answer: " ++ show result
|
||||||
|
Loading…
x
Reference in New Issue
Block a user