Can you explain how this Factorial function works?

后端 未结 5 1058
庸人自扰
庸人自扰 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:50

    I think you have to understand the logic of factorial.

    So factorial is just products, indicated by an exclamation mark ie, if you write

     0! = 1
     1! = 1
     2! = 2*1
     3! = 3*2*1
     4! = 4*3*2*1
     5! = 5*4*3*2*1
    

    Hope you find the pattern, so you can write the above factorials as:

     0! = 1
     1! = 1
     2! = 2*1!
     3! = 3*2!
     4! = 4*3!
     5! = 5*4!
    

    So in your function you are using the similar logic.

    Now in your function

    if(number == 0 || number == 1)
    {
       return 1;
    }
    

    The above logic is to cover the first two cases i.e, 0! and 1! And

    return number * Factorial(number -1);
    

    is for the rest of the numbers.

    So you are using the recursive technique of solving the factorial problem.

    To understand recursion, lets take a number say 5 i.e., we want find the value of 5!.

    Then first your function will check

    if(number == 0 || number == 1)
    

    which is not satisfied, then it moves to the next line ie,

    return number * Factorial(number -1); 
    

    which gives

    5*Factorial(5-1) which is equal to 5*Factorial(4)
    

    Now on subsequent calls to your Factorial function it will return the value like below:

    5*(4*Factorial(4-1)) which is equal to 5*(4*Factorial(3))
    5*(4*(3*Factorial(3-1)) which is equal to 5*(4*(3*Factorial(2)))
    5*(4*(3*(2*Factorial(2-1)))) which is equal to 5*(4*(3*(2*Factorial(1))))
    

    Now when it returns factorial(1) then your condition

    if(number == 0 || number == 1)
    

    is satisfied and hence you get the result as:

    5*4*3*2*1 = 120
    

    On a side note:

    Beware that factrial is used only for positive integers.

提交回复
热议问题