Can you explain how this Factorial function works?

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

    Recursion relies on what is called a base case:

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

    That if statement is called your base case. The base case defines when the recursion should stop. Note how you are returning 1 not returning the result of a call to the function again such as Factorial(number -1)

    If the conditions for your base case are not met (i.e. if number is NOT 1 or 0) then you proceed to call the function again with number * Factorial(number - 1)

提交回复
热议问题