This problem is very similar to several of the other prime generation problems, but being the dedicated blogger that I am here is 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.
- Generate primes using Sieve of Eratosthenes.
- Stop before reaching 2 million.
- Find the sum of this set of primes.
type public PrimesGenerator() =
member this.getPrimesMax max =
let primes = new BitArray(max+1, true)
let result = new ResizeArray(max/10)
for n = 2 to max do
if primes.[n] then
let start = (int64 n * int64 n)
if start < int64 max then
let i = ref (int start)
while !i <= max do primes.[!i] <- false; i := !i + n
member this.Problem9() =
let primesGen = new PrimesGenerator()
primesGen.getPrimesMax 2000000 |> Seq.map (fun prime -> (int64)prime) |> Seq.sum
Download the source code with unit tests.