Project Euler: Problem 9

Published:

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

a<b<ca2+b2=c2a < b < c \qquad a^2 + b^2 = c^2

For example,

32+42=9+16=25=523^2 + 4^2 = 9 + 16 = 25 = 5^2

There exists exactly one Pythagorean triplet for which,

a+b+c=1000a + b + c = 1000

Find the product abc.

Project Euler Problem 9

Solution

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.

public class PythagoreanTriples
    : 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);
  }

  IEnumerator IEnumerable.GetEnumerator()
  {
      return GetEnumerator();
  }
}

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:

var t = new PythagoreanTriples()
  .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 🙂