简体   繁体   中英

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

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.

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

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

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