Skip to content

Project Euler Problem 69

January 1, 2012

Project Euler Problem 69 solution is based on considerations taken from there and again capitalizes on infinite sequence of primes first time introduced in Problem 10 solution:

let rec primes = 
    Seq.cache <| seq { yield 2; yield! Seq.unfold nextPrime 3 }
and nextPrime n =
    if isPrime n then Some(n, n + 2) else nextPrime(n + 2)
and isPrime n =
    if n >= 2 then
        primes 
        |> Seq.tryFind (fun x -> n % x = 0 || x * x > n)
        |> fun x -> x.Value * x.Value > n
    else false

let problem069() =
    primes |> Seq.scan (fun acc x -> acc * x) 1
    |> Seq.takeWhile ((>) 1000000) |> Seq.max

Thanks to laziness of sequence computation, performance is on sub-millisecond level. Also this is a good example of functional approach power, where we do not know and do not care how much of primes sequence would be required; we just provide the infinite sequence generator tied with separate pertinent completion condition thru a combinator.

Advertisements

From → F#, Project Euler

Leave a Comment

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: