Here we generate a sequence of all possible triplets meeting the conditions, and find the first which is Pythagorean. It took a while to get this to perform well, my original solution required three nested loops and took several seconds to compute. By playing with the conditions a < b < c and a + b + c = 1000, and knowing the first Pythagorean triplet is (3,4,5), I was able to apply some bounds to a and b (though the upper bound for a will never trip when it’s piped into Seq.find). This solution takes a fraction of a second.
let problem9a = seq {for a in 3..332 do for b in 4..498 do yield (a, b, 1000 - a - b)} |> Seq.find (fun (a,b,c) -> (pown a 2) + (pown b 2) = (pown c 2)) |> (fun (a,b,c) -> a*b*c)
No comments:
Post a Comment