Recursion in PHP

0

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

I put a echo before the condition and in a decreasing way it displays 5 4 ... 1, I just can not understand where this return is going and how return $num will return the factorial if $num is equal (==) to 1, if someone can clarify me.

 function fatorial($num){
        echo $num; 
        if($num == 1){
            return $num;
        }
        return $num*fatorial($num-1);
    }
    echo fatorial(5);
    
asked by anonymous 13.12.2017 / 20:06

1 answer

2

When fatorial is called within:

return $num*fatorial($num-1);
The $num is subtracted by - (in fatorial($num-1) ), then the $num that started with 5 on the next call will be 4 , when it reaches fatorial($num-1); -1 again.

As ($num-1) has the value of 1 when calling fatorial() , it will enter its if , which compares if $num is equal to 1 %, then at this point the return "premature" will occur, which will end the function inside the if , which will return the current value return $num; which in this case is 1 itself.

Then the process will look like this:

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

  • The input will now be 4 (before finishing multiplication)

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

  • The input will now be 3 (before finishing multiplication)

  • ignores if ($num == 1)
  • The return "3 multiplies by% with%"

  • The input will now be fatorial(3-1) (before finishing multiplication)

  • ignores 2
  • The return "2 multiplies by% with%"

  • The input will now be if ($num == 1) (before finishing multiplication)

  • Enter%% of%
  • The return will return the value of fatorial(2-1) , which according to 1 is expected if ($num == 1) (will occur the $num "premature" I mentioned)

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

13.12.2017 / 22:25