cyphenom
cyphenom

Reputation: 33

Is finding the factorial of 5000 possible in javascript

I want to find the factorial of 5000 but once I try to pass 100 it'll return infinity. Is there are way to bypass this and get the result? I am trying to get the time it takes to solve this.

function testSpeed(n) {
    if (n > 0 && n <= 1) {
         return 1;
    } else {
         return n * testSpeed(n-1);
    }
}
console.log(testSpeed(5000));

Upvotes: 1

Views: 243

Answers (3)

Maxim Sibilev
Maxim Sibilev

Reputation: 1

I can receive for 170! maximum:

function factorial (y){
    if (y ==0 || y ==1){
        return 1;
    }
    else {
        f = y - 1;
        while (f >= 1) {
            y = y * f;
            f--;
        }
        return y;
    }
}
console.log(factorial(170));

Upvotes: 0

Scotty Jamison
Scotty Jamison

Reputation: 13199

As you've noticed, Javascript numbers can only get so big before they just become "Infinity". If you want to support bigger numbers, you'll have to use BigInt.

Examples:

// Without BigInt
console.log(100 ** 1000) // Infinity

// With BigInt
// (stackOverflow doesn't seem to print the result,
// unless I turn it into a string first)
console.log(String(100n ** 1000n)) // A really big number

So, for your specific bit of code, all you need to do is turn your numeric literals into BigInt literals, like this:

function testSpeed(n) {
  if (n > 0n && n <= 1n) {
      return 1n;
  } else {
      return n * testSpeed(n-1n);
  }
}

console.log(String(testSpeed(5000n)));

You'll find that youe computer can run that piece of code in a snap.

Upvotes: 6

dave
dave

Reputation: 64667

This seems to give the correct result (according to https://coolconversion.com/math/factorial/What-is-the-factorial-of_5000_%3F)

const longFactorial = (num) => {
   let result = num;
   for (let i = 1n; i < num; i++) {
      result = result * (num - i)
   }
   return String(result);
}
console.log(longFactorial(5000n));
 

Upvotes: 1

Related Questions