Project Euler: Problem 9

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

a < b < c \qquad a^2 + b^2 = c^2

For example,

3^2 + 4^2 = 9 + 16 = 25 = 5^2

There exists exactly one Pythagorean triplet for which,

a + b + c = 1000

Find the product abc.

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();
  }
}

Note: You can find the Triple class in the Lokad Shared Libraries.

And that’s pretty much what we need to solve this problem actually.

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 :)

About Torleif

Was born in Hønefoss (Norway) the 20th of January 1985 around 16:05. I am a Seventh-Day Adventist, a software developer and a hobby juggler.
This entry was posted in Project Euler, Software Development and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>