阶乘函数调用自身

时间:2018-09-04 17:03:20

标签: javascript function

我碰到了这个功能,该功能可以正常工作,但是我不明白为什么可以在factorial()函数中调用阶乘。有人可以向我解释。

function factorial(n) {
  if(n ==0) {
    return 1;
  }else{
    return factorial(n-1) *n;
  }
}
console.log(factorial(8));
//Logs 40320

3 个答案:

答案 0 :(得分:0)

这称为递归。什么是递归?

  

递归只是当函数调用自身时。

您可以在JavaScript here

中找到更多内容

答案 1 :(得分:-1)

这是称为递归的软件工程(数据结构和算法)概念。

递归是函数调用自身的编程概念。对于阶乘函数,根据观察,对于所有大于1的整数n,factorial(n) = n * factorial(n-1)。例如factorial(5) = 5 * factorial(4) 这意味着在实现中,该函数可以使用(n-1)进行调用,并将结果乘以n

您可以从here阅读更多内容。

递归具有advantages and disadvantages

答案 2 :(得分:-2)

请阅读此代码,它起作用。

 function factorialize(num) {
  // Step 1. Create a variable result to store num
  var result = num;
   
  // If num = 0 OR num = 1, the factorial will return 1
  if (num === 0 || num === 1) 
    return 1; 
 
  // Step 2. Create the WHILE loop 
  while (num > 1) { 
    num--; // decrementation by 1 at each iteration
    result = result * num; // or result *= num; 
    /* 
                    num           num--      var result      result *= num         
    1st iteration:   5             4            5             20 = 5 * 4      
    2nd iteration:   4             3           20             60 = 20 * 3
    3rd iteration:   3             2           60            120 = 60 * 2
    4th iteration:   2             1          120            120 = 120 * 1
    5th iteration:   1             0          120
    End of the WHILE loop 
    */
  }
     
  // Step 3. Return the factorial of the provided integer
  return result; // 120
}
console.log(factorialize(5));

相关问题