To practise writing a recursive function, I made a simple prime factor calculator. The function works - it determines and displays correctly in ascending order the prime factors of any integer up to 600,000 - but it always returns NULL.
I know the function could be structured differently etc etc. - it's the "why" of the NULL return that I want to understand!
In the code below, the parameters are as follows:
$original - the original value to be tested
$input - the value to be tested in the current iteration
$primes - array of primes
$divisors - array of prime factors determined
function determinePrimeFactors($original,$input,$primes,$divisors=[]) {
if ( $input !== 1 ) {
foreach ( $primes as $prime ) {
$quotient = $input / $prime;
if ( is_int($quotient) ) {
$quotients[] = $quotient;
}
}
$quotient = max($quotients);
$divisors[] = $input / $quotient;
determinePrimeFactors($original,$quotient,$primes,$divisors);
} else {
echo "<h1>RESULT</h1>";
echo "<p>".implode(" * ",$divisors)." = ".$original."</p>";
return $divisors;
}
}
The echo-ed output is always correct (e.g. 3 * 31 * 823 = 76539
).
I would expect the function to return the array which underlies the echo-ed output (e.g. [ 0=>3, 1=>31, 2=>823 ]
) - but instead it returns nothing.
Why is this?