Recursiveness in PHP

Asked

Viewed 386 times

0

Where does the return $num*fatorial($num-1); ?

I put a echo before the condition and decreasing form displays 5 4 ... 1, I just can’t figure out where this goes return and how return $num will return me the factorial if $num is equal(==) to 1, if someone can enlighten me.

 function fatorial($num){
        echo $num; 
        if($num == 1){
            return $num;
        }
        return $num*fatorial($num-1);
    }
    echo fatorial(5);
  • 1

    I explained it in a very simple and visual way on the Fibonacci calculation in Python. It’s not PHP, it’s not factorial, but the process is exactly the same. And it’s Python, so even if you never use the language, you’ll be able to understand what the code does (which is basically the same thing that yours does in PHP).

  • https://pt.wikipedia.org/wiki/Recursividade_(ci%C3%Aancia_da_computa%C3%A7%C3%A3o)

1 answer

3

When the fatorial is called within the:

return $num*fatorial($num-1);

The $num is subtracted by - (in fatorial($num-1)), then the $num that began with 5 next call will be 4, when you get to the fatorial($num-1); again will be reduced -1 again.

So ($num-1) has the value of 1 when calling the fatorial(), he’s gonna get into your if, which is to compare if $num is equal to 1, then at this moment the return "premature" that will end the function within the if, which will return the current value return $num; which in this case is 1 even.

Then the process will take place like this:

  • The input will be 5
  • ignores the if ($num == 1)
  • The return "5 multiplies by fatorial(5-1)"

  • The input will now be 4 (before the multiplication ends)

  • ignores the if ($num == 1)
  • The return "4 multiplies by fatorial(4-1)"

  • The input will now be 3 (before the multiplication ends)

  • ignores the if ($num == 1)
  • The return "3 multiplies by fatorial(3-1)"

  • The input will now be 2 (before the multiplication ends)

  • ignores the if ($num == 1)
  • The return "2 multiplies by fatorial(2-1)"

  • The input will now be 1 (before the multiplication ends)

  • Get in the if ($num == 1)
  • The return will return the value of $num, that in accordance with the if is expected 1 (will occur the return "premature" I quoted)

Now occurs the rest of the process back (recursiveness):

  • It was expected "2 multiplies by fatorial(2-1)", the last return was 1, so it is 2*1=2 and send for return

  • It was expected "3 multiplies by fatorial(3-1)", the last return was 2, so it is 3*2=6 and send for return

  • It was expected "4 multiplies by fatorial(4-1)", the last return was 6, so it is 4*6=24 and send for return

  • It was expected "5 multiplies by fatorial(5-1)", the last return was 24, so it is 5*24=120 and send for return

Browser other questions tagged

You are not signed in. Login or sign up in order to post.