Project Euler Problem 7 in F#

In the continuing series of solving Project Euler problems with F#, here is problem 7:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10,001st prime number?

  1. Generate primes using Sieve of Eratosthenes.
  2. Skip the first ten thousand primes and take the next one.

type public PrimesGenerator() =

member this.PrimesInfinite () =

let rec nextPrime n p primes =

if primes |> Map.containsKey n then

nextPrime (n + p) p primes


primes.Add(n, p)

let rec prime n primes =

seq {

if primes |> Map.containsKey n then

let p = primes.Item n

yield! prime (n + 1) (nextPrime (n + p) p (primes.Remove n))


yield n

yield! prime (n + 1) (primes.Add(n * n, n))


prime 2 Map.empty

member this.Problem7() =

let primes = new PrimesGenerator()

primes.PrimesInfinite() |> Seq.skip 10000 |> Seq.take 1 |> Seq.head

Download the source code with unit tests.


Leave a Reply

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

You are commenting using your 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