Search code examples
javascriptfactorial

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

Solution

  • 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.