我遇到了这个函数,它工作得很好,但我无法理解为什么会在fac引流()函数中调用factorial。谁能给我解释一下。
function factorial(n) {
if(n ==0) {
return 1;
}else{
return factorial(n-1) *n;
}
}
console.log(factorial(8));
//Logs 40320发布于 2018-09-04 17:14:58
请读这段代码--这是工作。
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));
发布于 2018-09-04 17:14:24
这是一个叫做递归的软件工程(数据结构和算法)概念。
递归是一个函数调用自己的编程概念。在阶乘函数的情况下,对于所有大于1的整数,factorial(n) = n * factorial(n-1)。例如,factorial(5) = 5 * factorial(4) --这意味着在实现中,函数可以用(n-1)调用自己,并将结果乘以n。
您可以从这里上读到更多信息。
递归有利害得失。
https://stackoverflow.com/questions/52171024
复制相似问题