Project Euler Problem 9 in F#

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

A Pythagorean triplet is a set of three natural numbers, a b c, for which,

a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

  1. Enumerate from 1 to 1000.  Create tuples of all sets (m, n) where m > n.
  2. Create Pythagorean triplets using Euclid’s formula from the tuples.
  3. Find the set where a + b + c = 1000.
  4. Find the product of this set.
let problem9 =
    let pythagorean_triplets(m:int, n:int) =
        let a = m*m-n*n
        let b = 2*m*n
        let c = m*m+n*n
        [a;b;c]
    let tops = 1000
    [for m in [1..tops] do
        for n in [1..m-1] do yield (m, n)] |> Seq.map (fun t -> pythagorean_triplets((fst t, snd t)))
            |> Seq.filter (fun x -> x |> Seq.sum = tops) |> Seq.head |> Seq.fold (fun acc elem -> acc * elem) 1

Download the source code with unit tests.

Advertisements

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