Reputation: 107
A Pythagorean triplet is a set of three natural number, a < b < c, for which a^2 + b^b = c^2. We are given the sum of Pythagorean triplet which is "number" in my case and we have to find the maximum product of a, b and c. I am giving input 5040 as it is the sum of 1260,1680 and 2100. These three numbers forms a Pythagorean triplet. My program should give 4445280000 output as it is the product of the numbers, but it is giving 150312704. Here is my code. I have watched the variables values of a b and c which are correct but the program is not printing the right product of it.
int noofcases = int.Parse(Console.ReadLine());
for (int i = 0; i < noofcases; i++)
{
int number = int.Parse(Console.ReadLine());
long result = -1;
int a, b, c;
for( a = 1; a <= number/3; a++)
{
b = (((number * number) - (2 * a * number)) / ((2 * number) - (2 * a)));
c = number - a - b;
if((a*a) + (b*b) == (c*c))
{
result = (a * b * c);
}
}
Console.WriteLine(result);
}
Upvotes: 0
Views: 70
Reputation: 16423
An int
in C# is a 32-bit signed integer, which has a range between -2,147,483,648 and 2,147,483,647.
This means that the maximum value that can be stored in an int
is 2,147,483,647. Your expected value, 4,445,280,000, is more than twice that maximum value.
When your int
value exceeds the maximum of 2,147,483,647, it will roll over to -2,147,483,648 and then count back to 0.
Therefore, 4,445,280,000 will become 150,312,704 as you are experiencing.
Using a long
for your result only will not work, because the output of any int
multiplied by an int
will always be an int
unless you use explicit casting.
Simply switch your int
s to long
s in your program and it will operate as you expect:
int noofcases = int.Parse(Console.ReadLine());
for (int i = 0; i < noofcases; i++)
{
long number = int.Parse(Console.ReadLine());
long result = -1;
long a, b, c;
for (a = 1; a <= number / 3; a++)
{
b = (((number * number) - (2 * a * number)) / ((2 * number) - (2 * a)));
c = number - a - b;
if ((a * a) + (b * b) == (c * c))
{
result = (a * b * c);
}
}
Console.WriteLine(result);
}
Output:
1
5040
4445280000
Upvotes: 1