Welcome to week 9 of my Project Euler series.
Problem 9:
Find the only Pythagorean triplet, {a, b, c}, for which a + b+ c = 1000.Details:
A Pythagorean triplet is a set of three natural numbers, a
b
c, for which,a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Code:
// Find the only Pythagorean triplet, {a, b, c}, for which a + b + c = 1000.
class Problem0009
{
static void Main(string[] args)
{
int answer = 0;
for (int a = 1; a < 500; a++) // a + b + c = 1000 so a and b can not be more than 500
{
for (int b = a; b < 500; b++)
{
int c = 1000 - a - b;
if ((a * a) + (b * b) == (c * c))
{
answer = a * b * c;
break;
}
}
if (answer > 0)
break;
}
Console.Write(answer);
Console.ReadLine();
}
}
Solution:
This one was once again pretty simple (I am really going to miss being able to say that in a couple of weeks). The details do an adequate job of explaining a Pythagorean triplet so there is no need to reiterate that here, but one thing that will make life easier is keeping in mind that the sum of the three numbers has to be 1000. That allowed me to shrink my for statement down to only include numbers less than (exclusive) 500. I could have in all honesty shrunk it down quite a bit further, but finding that fine line was not really worth the effort. There was no chance that one of the numbers could be over 500 since 'b' has to be bigger than 'a' and there sum has to be 1000.
Once getting a grip on that and putting my two for statements in place I just go ahead and figure out what 'c' would be given the other two numbers and check if they are in fact a Pythagorean triplet. If they are I have my answer and since it is explicitly stated in the problem that there is only one I went ahead and added a break in. No point in searching for an answer that I already have.
Next week is going to get a bit tricky to be honest so make sure and check it out. Until next time...
Enjoy!
0 comments:
Post a Comment