Find the only Pythagorean triplet, {a, b, c}, for which a + b+ c = 1000.
A little bit of research on Wikipedia led to the page on Pythgorean triples. Using Euclid's formula we can generate a sequence of tuples which can be manipulated to find the desired answer:
let triples = seq {
for n in 1..100 do
for m in n+1..100 do
yield (2*m*n, m*m-n*n, m*m+n*n)
}Note that my selection of 100 as the endpoint for each of the loops is pretty arbitrary. I just needed a number big enough that the triple whose members summed to 1000 would be included in the sequence. Then to find the right one we can write:
triples |> Seq.find (fun (a, b, c) -> a+b+c = 1000) |>
(fun (a, b, c) -> a*b*c) |>
printfn "product = %A"This sequence is lazily evaluated until we find the one we're looking for.

No comments:
Post a Comment