I’ve written a program that must find the solution to a EulerProblem. I want to train my program skills that’s why I’ve signed up on euler.
This is the problem:
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.
and this is my code, but it runs soo slow, it take hours to give me the right abc.
static int findTriplet(int getal)
{
boolean test = false;
for(int a = 1; !test; a++)
for(int b = a+1; !test; b++)
for(int c = b+1; !test; c++)
{
if( a*a + b*b == c*c)
{
if(a+b+c == getal)
{
return (a*b*c);
}
}
}
return 0;
}
Is it possible to make the code much faster or is it normal that it takes hours?
Kind regards,
EDIT:
Thanks for helping. The !test boolean was useless sorry for that, This works :
static int findTriplet(int getal)
{
for(int a = 1; a < 1000; a++)
for(int b = a+1; b < 1000; b++)
for(int c = b+1; c < 1000; c++)
{
if( a*a + b*b == c*c)
{
if(a+b+c == getal)
{
return (a*b*c);
}
}
}
return 0;
}
I’ve also wrote a haskell variation that also does the trick.
Think this was easier in Haskell and more efficient.
Thaks for the tips.
In order to optimize this naive algorithm, you have first to understand that :
false. You also take the risk to encounter an overflow ofc.Now, you know that you need to :
Here are some hints for easy optimisations :
And some hints for harder optimisations :