The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
In [12]:
let compositesInRange fromNum toNum =
[|2 .. toNum/fromNum|]
|> Array.map (fun x -> fromNum * x)
let primesTo n =
// start off assuming every number from 0 .. n is prime
let isPrime = Array.init (1+n) (fun _ -> true)
// simple sieve of eratosthenes - update "primeness" of
// each number in the isPrime array
for x in 2 .. int(sqrt(double(n))) do
if isPrime.[x] then
compositesInRange x n
|> Array.map (fun i -> isPrime.[i] <- false)
|> ignore
// now return numbers which are "true" in isPrime array
[|2..n|]
|> Array.filter (fun x -> isPrime.[x])
|> Array.map uint64
// pick a big number, hopefully we have enough primes!!
primesTo 2000000
|> Array.sum
Out[12]:
In [ ]: