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.
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();
}
Further optimization from Oleg's answer. One side cannot be greater than the sum of the other two. So a + b cannot be less than 500.
While as many people have pointed out that your code will work fine once you switch to using
pow
. If your interested in learning a bit of math theory as it applies to CS, I would recommend trying to implementing a more effient version using "Euclid's formula" for generating Pythagorean triples (link).I know this question is quite old, and everyone has been posting solutions with 3 for loops, which is not needed. I got this solved in O(n), by
**equating the formulas**; **a+b+c=1000 and a^2 + b^2 = c^2**
So, solving further we get;
If we solve further we deduce it to;
I'm afraid
^
doesn't do what you think it does in C. Your best bet is to usea*a
for integer squares.I think the best approach here is this:
explanation: We shall refer to the N and A constant so we will not have to use two loops. We can do it because
c=n-a-b
and b=(a^2-(a-n)^2)/(2(a-n))
I got these formulas by solving a system of equations:a+b+c=n
,a^2+b^2=c^2
As mentioned above, ^ is bitwise xor, not power.
You can also remove the third loop, and instead use
c = 1000-a-b;
and optimize this a little.Pseudocode