Project Euler — Problem 7 Solution

Problem

By list­ing the first six prime num­bers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime num­ber?

Solution

open System

let findFactorsOf(n) =
    let upperBound = int32(Math.Sqrt(double(n)))
    [2..upperBound]
    |> Seq.filter (fun x -> n % x = 0)

let isPrime(n) = findFactorsOf(n) |> Seq.length = 0
let primeNumbers = Seq.unfold (fun x -> Some(x, x + 1)) 2 |> Seq.filter isPrime
let p = primeNumbers |> Seq.nth(10000)

Here I bor­rowed the find­Fac­tors and isPrime func­tions I first used in the prob­lem 3 solu­tion, except this time they don’t have to be con­strained to work int64 types.

The rest of the solution’s pret­ty straight for­ward too, to find the 10001st prime num­ber I first need to gen­er­ate the sequence of all prime num­bers. I did so by using Seq.unfold to gen­er­ate the list of all nat­ur­al num­bers equal or greater than 2 (the first prime num­ber), cou­pled with the isPrime pred­i­cate:

let primeNumbers = Seq.unfold (fun x -> Some(x, x + 1)) 2 |> Seq.filter isPrime

With the sequence of all prime num­bers at hand, Seq.nth is used to find the ele­ment at the index posi­tion 10000 (sequences are zero-indexed like arrays, so this is actu­al­ly the 10001st ele­ment in the sequence) to get our answer!