Project Euler Problem 10 in F#

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.

  1. Generate primes using Sieve of Eratosthenes.
  2. Stop before reaching 2 million.
  3. 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

result.Add n

result

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.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s