Can you explain how this Factorial function works?

后端 未结 5 1069
庸人自扰
庸人自扰 2020-12-21 19:26

I understand that \"a\" solution is:

function Factorial(number)
{
    if(number == 0 || number == 1){
        return 1         


        
5条回答
  •  长情又很酷
    2020-12-21 19:46

    It is called recursion.

    This function is called like this

    var result = Factorial(3); in Factorial function

    First time return 3*Factorial(2);

    Now here return statement doesnt get executed insted Factorial is called again.. so second time return 2*Factorial(1);

    again in Factorial(1) Third time return 1;

    So go to second return 2*1;

    Next to first return 3*(2*1);

    Finally var result = 3*2*1 = 6.

提交回复
热议问题