首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >阶乘函数调用本身

阶乘函数调用本身
EN

Stack Overflow用户
提问于 2018-09-04 17:03:19
回答 2查看 124关注 0票数 0

我遇到了这个函数,它工作得很好,但我无法理解为什么会在fac引流()函数中调用factorial。谁能给我解释一下。

代码语言:javascript
复制
function factorial(n) {
  if(n ==0) {
    return 1;
  }else{
    return factorial(n-1) *n;
  }
}
console.log(factorial(8));
//Logs 40320
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-04 17:14:58

请读这段代码--这是工作。

代码语言:javascript
复制
 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));

票数 -2
EN

Stack Overflow用户

发布于 2018-09-04 17:14:24

这是一个叫做递归的软件工程(数据结构和算法)概念。

递归是一个函数调用自己的编程概念。在阶乘函数的情况下,对于所有大于1的整数,factorial(n) = n * factorial(n-1)。例如,factorial(5) = 5 * factorial(4) --这意味着在实现中,函数可以用(n-1)调用自己,并将结果乘以n

您可以从这里上读到更多信息。

递归有利害得失

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52171024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档