简体   繁体   中英

How to find factorial of 25 in javascript

When I used

function processData(input) {`console.log(fact(input));`}

function fact(input) {
  if (input == 1 || input == 0) {
    return input;
  } else {
    return input * fact(input - 1);
  }
}

I get output is:

1.5511210043330986e+25

but I need :

15511210043330985984000000

what I do for This output. I am not able to include any library because it was online test and I don't have permission to add libraries.

In JavaScript, numbers have insufficient precision to represent all the digits of 25!, so simply calculating 25 * 24 * ... * 1 will yield an incorrect result.

To work with large numbers, the best approach is to use an arbitrary-precision integer library, like BigInteger.js , that's been thoroughly tested. But even if you can't use a library, you can still calculate 25! by breaking the result into smaller chunks:

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

Note that this code does the bare minimum to calculate 25!. For larger values of n, more chunks need to be added.

if you want that kind of output you need to use a library that handles numbers differently than Javascript does. It's called BigNumber.js

your code would look like this:

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());

You can use BigInt in a recursive function like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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