Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find factorial of 25 in javascript

Tags:

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.

like image 312
nitesh singh Avatar asked Dec 19 '22 01:12

nitesh singh


1 Answers

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.

like image 187
Michael Liu Avatar answered Dec 24 '22 02:12

Michael Liu