Improve Haskell solution for Problem 10 using prime sieve

This commit is contained in:
daniele 2024-11-23 17:46:34 +01:00
parent e31b25846c
commit de4106efe7
Signed by: fuxino
GPG Key ID: 981A2B2A3BBF5514
2 changed files with 7 additions and 5 deletions

View File

@ -1,5 +1,6 @@
module ProjectEuler
( isPrime
, primeSieve
, lcmm
, digitSum
, sumProperDivisors
@ -9,6 +10,7 @@ module ProjectEuler
import Data.Char (digitToInt)
import Data.List (nub)
import Data.List.Ordered (minus, unionAll)
isPrime :: (Integral n) => n -> Bool
isPrime 1 = False
@ -19,6 +21,9 @@ isPrime n =
where candidates = [5,11..limit]
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 values
| length values == 2 = lcm (head values) (last values)

View File

@ -2,12 +2,9 @@
--
-- Find the sum of all the primes below two million.
import ProjectEuler (isPrime)
sumPrimes :: Int -> Int
sumPrimes n = sum [ x | x <- [1..n], isPrime x ]
import ProjectEuler (primeSieve)
main = do
let result = sumPrimes 2000000
let result = sum $ takeWhile (<2000000) primeSieve
putStrLn $ "Project Euler, Problem 10\n"
++ "Answer: " ++ show result