简体   繁体   English

尝试使用 javascript 使用递归打印数字的阶乘,但没有给出预期的输出

[英]Trying to print the factorial of a number with recursion using javascript but its not giving the expected output

Trying to print the factorial of a number with recursion using javascript but its not giving the expected output.尝试使用 javascript 使用递归打印数字的阶乘,但没有给出预期的输出。

function factorialRecursion(n){
return n * factorialRecursion(n - 1);
}
factorialRecursion(6);

Uncaught RangeError: Maximum call stack size exceeded at factorialRecursion (eval at factorial ( enter code here index.html:3), :1:28) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13)未捕获的 RangeError: 在 factorialRecursion (eval at factorial ( enter code here index.html:3), :1:28) at factorialRecursion (eval at factorial (index.html:3), :3:13) 时超出了最大调用堆栈大小factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3) , :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13) at factorialRecursion (eval at factorial (index.html:3), :3:13 )

The stack overflows because there is no base case .堆栈溢出,因为没有基本情况

  • to calculate factorial(6) , you need to know the answer to factorial(5)要计算factorial(6) ,您需要知道factorial(5)的答案
  • to calculate factorial(5) , you need to know the answer to factorial(4)要计算factorial(5) ,您需要知道factorial(4)的答案
  • ... ...
  • to calculate factorial(1) , you need to know the answer to factorial(0)要计算factorial(1) ,您需要知道factorial(0)的答案
  • to calculate factorial(0) , you need to know the answer to factorial(-1)要计算factorial(0) ,您需要知道factorial(-1)的答案
  • to calculate factorial(-1) , you need to know the answer to factorial(-2)要计算factorial(-1) ,您需要知道factorial(-2)的答案
  • ... ...

Above we see the original program just continues n - 1 infinitely, until the stack overflows.上面我们看到原始程序只是无限地继续n - 1 ,直到堆栈溢出。

A fix to your program might look like -对您的程序的修复可能看起来像 -

 function factorial(n) { if (n <= 0) // <-- base case return 1 else // <-- inductive case (n > 0) return n * factorial(n - 1) } console.log(factorial(6)) // 720

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM