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

Published Tuesday, August 26, 2008 5:22 PM by PSteele
Filed under: ,

Comments

# re: Project Euler #9

You can leave out the c loop and just set c = 1000 - a - b.

Wednesday, August 27, 2008 7:34 AM by Ant

# re: Project Euler #9

Ah yes!! Very nice.

Wednesday, August 27, 2008 7:52 AM by PSteele

# Euler 10

After tackling number 9 yesterday , I thought I'd do #10 real quick since it seemend pretty easy. Calculate

Wednesday, August 27, 2008 9:10 AM by Patrick Steele's .NET Blog

# Euler 10

After tackling number 9 yesterday , I thought I&#39;d do #10 real quick since it seemend pretty easy

Wednesday, August 27, 2008 9:22 AM by Patrick Steele