Double for loop not working
Im trying to solve Euler's Project 9 using PHP. Im pretty sure my logic is fine, but my double for-loop only goes through the first loop, completes the second loop and stops. Any1 knows what Im doing wrong? I want to do the first one 998 times and the second one 998 times. ( NB: I know that I can optimize the code because I $ will never be higher then 331 due to a
//
//A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
//a² + b² = c²
//
//For example, 3² + 4² = 9 + 16 = 25 = 5².
//
//There exists exactly one Pythagorean triplet for which a + b + c = 1000.
//Find the product abc.
$na = array();
$a=1;
$b=1;
$c=0;
$z=998;//upper bound
for($a;$a<$z;$a++){
for($b;$b<$z;$b++){
$c=(1000-$a)-$b;
if(($a*$a)+($b*$b)==($c*$c))
echo "played: $a + $b + $c = 1000<br />";
}
}
Result is (When I comment the if out) : played: 1 + 1 + 998 = 1开发者_JS百科000 to played: 1 + 997 + 2 = 1000
Your variable $b
is never reset so it will always be equal to $z
after the first time in the inner loop.
What you need is
...
for($b = 1; $b < $z; $b++) {
...
You need to reset $b
on every iteration of the outer loop.
Here you go.
for($a = 1;$a<$z;$a++){
for($b = 1;$b<$z;$b++){
$c=(1000-$a)-$b;
if(($a*$a)+($b*$b)==($c*$c))
echo "played: $a + $b + $c = 1000<br />";
}
}
精彩评论