Rahul - 4 months ago 8

C Question

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a^{2} + b^{2} = c^{2}

For example, 3^{2} + 4^{2} = 9 + 16 = 25 = 5^{2}.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.

Find the product abc.

*Source*: http://projecteuler.net/index.php?section=problems&id=9

I tried but didn't know where my code went wrong. Here's my code in C:

`#include <math.h>`

#include <stdio.h>

#include <conio.h>

void main()

{

int a=0, b=0, c=0;

int i;

for (a = 0; a<=1000; a++)

{

for (b = 0; b<=1000; b++)

{

for (c = 0; c<=1000; c++)

{

if ((a^(2) + b^(2) == c^(2)) && ((a+b+c) ==1000)))

printf("a=%d, b=%d, c=%d",a,b,c);

}

}

}

getch();

}

Answer

```
#include <math.h>
#include <stdio.h>
int main()
{
const int sum = 1000;
int a;
for (a = 1; a <= sum/3; a++)
{
int b;
for (b = a + 1; b <= sum/2; b++)
{
int c = sum - a - b;
if ( a*a + b*b == c*c )
printf("a=%d, b=%d, c=%d\n",a,b,c);
}
}
return 0;
}
```

explanation:

- b = a;

if a, b (a <= b)) and c are the Pythagorean triplet,

then b, a (b >= a) and c - also the solution, so we can search only one case - c = 1000 - a -b; it's one of the conditions of the problem (don't need to scan all possible 'c': just calculate it)