Skip to content
Advertisement

Understanding prime factor decomposition function in PHP?

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:

  1. Isn’t the while() loop always satisfied in the case of 6? Doesn’t 6 % 2 always equal 0?

  2. I don’t quite get the if($cnt) so if it’s true or 1 then concatenate $factors to itself and the strval() 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

  1. The value of $n changes each time through the loop. Since 6 % 2 == 0 is true, it executes the statement $n = $n / $i;. This sets $n to 3, so the next time it tests 3 % 2 == 0. This time the test fails, so the loop stops.

  2. 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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement