Project Euler #9

So I decided to start looking into the Project Euler problems.  A number of fellow SRT employees have been tackling these over the past few months and after recently reading Bill's solutions for problems #7 and #8 I decided to look at #9.

Find the only Pythagorean triplet, {a, b, c}, for which a + b + c = 1000.

I thought about this for quite a while.  I was trying to see how I could utilize LINQ to make this easier.  In the end, I decided to just use the brute force method of nested loops:

private static void Euler9()
{
    for (int a = 0; a < 1000; a++)
    {
        for (int b = a + 1; b < 1000; b++)
        {
            for (int c = b + 1; c < 1000; c++)
            {
                if (a + b + c == 1000 && (Math.Pow(a, 2) + Math.Pow(b, 2) == Math.Pow(c, 2)))
                {
                    Console.WriteLine("{0},{1},{2}", a, b, c);
                    return;
                }
            }
        }
    }
}

I added a few optimizations in an effort to speed this up:

  • Since a+b+c has to equal 1000, no single element (a or b or c) can be greater than 1000.  Therefore my loops are pretty short.
  • I took advantage of C#'s short-circuiting to do the simple "a + b + c == 1000" check before doing the squares.

It runs pretty quick (under a second).  The first time I ran it I took out the "return" to make sure my logic only produced a single result.  It did!  :)

2 Comments

Comments have been disabled for this content.