A Pythagorean triplet is a set of three natural numbers, for which,
There exists exactly one Pythagorean triplet for which,
Find the product abc.
This I wasn’t quite sure how to solve effectively and my solution is probably not the fastest or most clever, but at least it is pretty simple 🙂 To start off, we need a source of Pythagorean triplets.
: IEnumerable<Triple<ulong, ulong, ulong>>
public IEnumerator<Triple<ulong, ulong, ulong>> GetEnumerator()
for (ulong c = 1;; c++)
for (ulong b = 1; b <= c; b++)
for (ulong a = 1; a < b; a++)
if ((a*a) + (b*b) == c*c)
yield return Tuple.From(a, b, c);
You can find the Triple class in a library called the Lokad Shared Libraries.
Anyways, that’s pretty much what we need to solve this problem actually. We can use it like so:
.First(x => x.Item1 + x.Item2 + x.Item3 == 1000);
var answer = t.Item1 * t.Item2 * t.Item3;
This piece of code simply goes through triplets until it finds the first one fulfilling our requirement. It runs in around 230 milliseconds, which is acceptable enough.
Do you have a more clever way to do this? Please leave a comment and share 🙂