如何在javascript中找到25的阶乘

How to find factorial of 25 in javascript

本文关键字:阶乘 javascript      更新时间:2023-09-26

当我使用

function processData(input) {`console.log(fact(input));`}
function fact(input) {
  if (input == 1 || input == 0) {
    return input;
  } else {
    return input * fact(input - 1);
  }
}

我得到的输出是:

1.5511210043330986e+25

但是我需要:

15511210043330985984000000

我对这个输出做了什么。我不能包含任何库,因为它是在线测试,我没有权限添加库。

在JavaScript中,数字没有足够的精度来表示25的所有数字!,所以简单地计算25 * 24 * ... * 1会得到一个不正确的结果。

要处理大数,最好的方法是使用任意精度的整数库,比如BigInteger.js,它已经经过了彻底的测试。但即使你不能使用库,你仍然可以计算25!通过将结果分成更小的块:

function factorial(n) {
    var x = [1, 0];     // Two chunks are enough to represent 25!
    var base = 1e18;    // Each chunk x[0] and x[1] stores a number from 0 to (base - 1).
    function pad(i) {   // Pad a chunk with 0's on the left to 18 digits.
        return (i + base).toString().substr(1);
    }
    function trim(s) {  // Remove all leading 0's from the string s.
        return s.match(/[1-9].*/)[0];
    }
    for (; n > 1; n--) {
        x[0] *= n;
        x[1] *= n;
        if (x[0] >= base) {
            var carry = Math.floor(x[0] / base);
            x[1] += carry;
            x[0] -= carry * base;
        }
    }
    return trim(x[1].toString() + pad(x[0]));
}
console.log(factorial(25)); // 15511210043330985984000000

请注意,这段代码只做了最小的计算25!对于较大的n值,需要添加更多的块

可以在递归函数中使用BigInt:

 const factorialize = (num) => {
   if (num === 0n) return 1n;
   return num * factorialize(num - 1n);
 };
 console.log(String(factorialize(BigInt(25))));

如果您想要这种输出,则需要使用与Javascript处理数字不同的库。它叫做bignnumber。js

你的代码看起来像这样:

function processData(input) { console.log(fact(input).toFormat().replace(/',/g, "")); }
function fact(input) {
    if(typeof input != "object")
         input = new BigNumber(input);
    if(input.equals(1) || input.equals(0))
         return input;
    return input.times(fact(input.minus(1)))
}

您可以使用BigInt:

console.log(BigInt(Array.from(Array(25),(_,i)=>BigInt(i+1)).reduce((a,b)=>BigInt(a)*BigInt(b))).toString());