JavaScript - 阶乘解释

标签 javascript recursion factorial

我希望有人基本上帮助我理解每行代码在做什么,并帮助我注释每一行(如果适用),以便它可以帮助向另一个人解释它在做什么。如果有人能够再看一眼并确保代码实际上是好的,那就太棒了 - 我正在尝试了解阶乘/递归,并做了一些研究并找到了这些解决方案。

我得到了这样的场景:

对于正 n,阶乘为 n! = n(n−1)! (例如 5!= 5 * 4 * 3 * 2 * 1)*

以下是我针对此场景找到的内容:

// Prompt user to enter a number to calculate the factorial
var num = prompt("What number do you want to find the factorial of?");

var factorial = function(n) {
    if (n == 0) {
        return 1;
    } else {
        product = 1;
        for (i = 1; i < n; i++) {
            product *= i;
        }
        return product;
    }
}
console.log(factorial(num));

递归

创建递归算法以每秒计算阶乘 数量如下例所示:

5! = 5 * 3 * 1 = 15 6! = 6 * 4 * 2 = 48

至于草书部分,将其添加到上面的代码中,编写如下 -

//  recursive
var factorial = function(n) {
    if (n == 0) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}
console.log(factorial(num));

非常感谢您对此提供的帮助 - 如果该问题已得到解答,则深表歉意;如果该问题已发布,请引导我到另一个线程。谢谢!

最佳答案

为此您不需要递归:

/**
 * Calculate factorial, optionally using a difference other than 1 with previous value.
 * Example: factorial(6, 2) // 6*4*2 = 48
 */
var factorial = function(n, d) {
  if (!d) {d = 1;}
  var product = 1;
  while (n > 1) {
    product *= n;
    n -= d;
  }
  return product;
};

console.log(factorial(6, 2)); // 48
console.log(factorial(6)); // 720

注意:在函数内部使用关键字“var”声明局部变量。否则它们将成为全局变量,并且您第二次尝试使用函数可能会产生错误的结果。

关于JavaScript - 阶乘解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40474233/

相关文章:

c++ - 尝试在 cpp 中打印 n 维数组

javascript - 在 div 标签 JS 后设置光标位置

javascript - 如何为一个 div 设置动画以显示并移动到另一个 div 上方

javascript - 为什么 youtube 视频没有使用 Jquery 在 iframe 中加载?

C程序: Recursive ordering function printing incorrectly

c - x86 汇编中的递归函数

algorithm - 如何计算实数的逆阶乘?

c# - 需要递归地生成文件数组的每个唯一组合

python - Python 中的阶乘求和

javascript - JavaScript 中要忽略的单词列表?