-1

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?

hnmcc
  • 121
  • 1
  • 10
  • 1
    you have no return if `if` is true . Semms, `return determinePrimeFactors($original,$quotient,$primes,$divisors);` – splash58 Sep 23 '19 at 14:21
  • You got null because on the last line executed on your code will be the `determinePrimeFactors($original,$quotient,$primes,$divisors);` at the end of the `if`, or this line return nothing, you do noy pass in the `else` clause and you got `NULL` at the end. – GrenierJ Sep 23 '19 at 14:22

1 Answers1

4

Add return in your previous calls to carry forward that return value till the first call and ultimately return it from the function.

return determinePrimeFactors($original,$quotient,$primes,$divisors);

Also, with the above return, you could make your code much cleaner by removing the redundant else part.

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;

        return determinePrimeFactors($original,$quotient,$primes,$divisors);
    }

    echo "<h1>RESULT</h1>";
    echo "<p>".implode(" * ",$divisors)." = ".$original."</p>";

    return $divisors;
} 
nice_dev
  • 17,053
  • 2
  • 21
  • 35