Euler Problem 9

I was going to wait a bit to post this, but Patrick Steele posted his solution, so I figured I should post mine.

Patrick took the straight out brute force approach. I decided to think a bit differently and use the some LINQ code to generate my answer.

The problem is to find the only Pythagorean triplet {a,b,c} for which a + b + c = 1000.

The first step was to find a sequence of all triples {a,b,c} where a+b+c added to 1000. To save a little computing time, I made use of two important facts. First, in order to be a Pythagorean triplet, c must be greater than both a and b. Second, different orders of a and b don't matter: {3,4,5} would be the same as {4,3,5}. Therefore, I made the assumption that a must be less than or equal to b.

From those possible answers, I needed to find the only triplet that is a Pythagorean triplet. Here's the code:

 

   1: static void Main(string[] args)
   2: {
   3:     var possible = from A in Enumerable.Range(1, 333)
   4:                    from B in Enumerable.Range(A, (1000 - A) / 2 - A)
   5:                    let C = 1000 - A - B
   6:                    select new { A, B, C };
   7:     var answer = (from triple in possible
   8:                   where triple.A * triple.A + triple.B * triple.B == triple.C * triple.C
   9:                   select triple).Single();
  10:  
  11:     Console.WriteLine(answer);
  12:     Console.WriteLine(answer.A * answer.B * answer.C);
  13: }

There are two bits of LINQ goodness here that I haven't mentioned before.

First, there's the call to Single(). Single will throw an exception if the sequence does not contain exactly one answer. That helps me test: there must be exactly one.

Second, the C# compiler creates an override for ToString() in every anonymous type. That override writes the value of all the properties in the anonymous type. That's why I can simply use Console.Writeline(answer) to see the values of a,b,c.

It's just language goodness.

Published 28 August 2008 02:03 PM by wwagner
Filed under: , , ,
Ads by Lake Quincy Media

Comments

# Koen said on 29 August, 2008 07:17 AM

I guess you want to add A, B and C in the last line rather than multiplying them...

# Sobre C#, LINQ y algo más... said on 29 August, 2008 08:22 AM

Revisando nuevos enlaces aparecidos durante agosto en la página de C# de MSDN, he dado con el blog de

# Octavio Hernandez said on 29 August, 2008 08:37 AM

Bill,

The nature of this problem and of your and Patrick's solutions closely resemble those of a problem/solutions I posted in my blog some time ago:

geeks.ms/.../should-we-learn-a-new-way-of-writing-loops.aspx

Regards,

Octavio

Search

Go

Blog Group Links

Nascar style badges