Project Euler 007 – F#

14 03 2011

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 10001st prime number?

Solution

(*

 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 10001st prime number?

*)

 

let primes =

  let rec prim n (sofar: list<int>) =

      seq { if (sofar |> List.forall (fun i -> n%i <> 0)) then

                yield n

                yield! prim (n+1) (n :: sofar)

            else

                yield! prim (n+1) sofar }

  prim 2 []

 

let tenthousandfirst = primes

                       |> Seq.take 10001

                       |> Seq.max

 

printfn "%A" tenthousandfirst

 

Discussion

The primes function was posted on a forum by Don Syme.  The use of the infinite sequence is just awesome – again.  20+ years of imperative programming has taken it’s toll so it’s going to take a lot more effort on my part to wrap my mind around this functional stuff.  I’ll keep plugging away.

If you have any questions, leave a comment, find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).