Hello I'm Andrea and I'm a beginner to programming,
I' m trying to solve the Project Euler - problem 3, but I can't understand why the "j" doesn't exit from the while loop ( It generates an infinite loop ).
When the "j" enters in the else (inside the while) the "$prime" variable value is set to true, so I suppose the program has to exit from the while loop (because the second condition: while ( $j < $i || $prime != true || $noPrime != true )), but the program continues to go on.
I know the code is not complete for the problem and not beautiful too, but I'm really stuck on this problem.
Code below:
<body>
<?php
$num = 20;
$z = 0; $j = 2;
$fPrimes = [];
$prime = false;
$noPrime = false;
$primeFactor = 0;
for ($i=2; $i < 20; $i++) { //check for every number under the $num
echo "<b>My i : " . $i . "</b><br>";
if ($num % $i == 0) { //check if is a divisor
$j = 2;
if ($i == 2) $j = 1;
while ( $j < $i || $prime != true || $noPrime != true ) {
echo "My j : " . $j . "<br>";
if ($i % $j != 0) { // j is not a divisor
echo "My j : " . $j . " not a divisor<br>";
}elseif ($i % $j == 0 && $j != $i && $j != 1) { // j = divisor but not =$i and not =1
echo $i . " Not f.prime!<br>";
$noPrime = true;
}else{ // j is a divisor and prime factor
echo $i . " It's a f.prime!<br><br>";
$primeFactor [$z] = $i;
$prime = true;
$z++ ;
}
if ($prime == false && $noPrime == false) $j++;
}
$prime = false;
$noPrime = false;
}else echo "<br>" . $i . " Not divisor.</br><br>";
}
for ($i=0; $i < count($primeFactor ) ; $i++) echo $primeFactor [$i] . " ";
?>
</body>
Here below the result:
My i : 2
My j : 1
2 It's a f.prime!
My j : 1
2 It's a f.prime!
.. infinite loop
My j : 1
2 It's a f.prime!
Thanks in advance for the help