计算阶乘

Author Avatar
tanglijun 7月 22, 2017

JavaScript 中的阶乘算法

递归算法

function factorial(number) {
  if (number === 1) {
    return number
  } else {
    return number * factorial(number - 1)
  }
}

迭代算法

function factorial(number) {
  var multiplicand = 1

  for (; number > 1; number --) {
    multiplicand *= number
  }

  return multiplicand
}

利用 reduce() 或 reduceRight() 方法

function factorial(number) {
  var numbers = [];

  for (var i = number; i > 0; i -= 1) {
    numbers.push(i);
  }

  return numbers.reduce(function (accumulator, currentValue) {
    return accumulator * currentValue;
  })
}
function factorial(number) {
  var numbers = [];

  for (var i = number; i > 0; i -= 1) {
    numbers.push(i);
  }

  return numbers.reduceRight(function (accumulator, currentValue) {
    return accumulator * currentValue;
  })
}

许可协议:署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
本文链接:https://tanglj.cn/2017/07/22/factorial/