I’m having a hard time understanding part of this function. It takes an input and prints the prime decomposition of it starting with 2.
I’m confused about 2 parts:
Isn’t the
while()
loop always satisfied in the case of 6? Doesn’t 6 % 2 always equal 0?I don’t quite get the
if($cnt)
so if it’s true or 1 then concatenate$factors
to itself and thestrval()
but why add it to itself if it was an empty string beforehand? Can anyone explain this clearer than my poor understanding? I really wanna understand it better. Thank you.function primeFactors($n) { if ($n < 2) return "(".strval($n).")"; $factors = ""; for ($i = 2; $i <= $n; $i++) { $cnt = 0; while ($n % $i == 0) { $cnt++; $n = $n / $i; echo $cnt . " "; } if ($cnt) { $factors = $factors . "(".strval($i); if ($cnt > 1) { $factors = $factors . "**".strval($cnt); } $factors .= ")"; } } echo $factors; return $factors; } primeFactors(6); // (2)(3)
Advertisement
Answer
The value of
$n
changes each time through the loop. Since6 % 2 == 0
is true, it executes the statement$n = $n / $i;
. This sets$n
to3
, so the next time it tests3 % 2 == 0
. This time the test fails, so the loop stops.Any non-zero value is true, so the
if ($count)
block is executed whenever$i
is a factor of$n
.
Why add it to itself if it was an empty string beforehand?
$factors
is only an empty string when the function first starts. After it finds the first factor, it contains that factor. And each time it finds another factor, it adds the new factor to the end of this string.