[英]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.我想找到 5000 的阶乘,但一旦我尝试超过 100,它就会返回无穷大。 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".正如您所注意到的,Javascript 个数字在变成“无穷大”之前只能变得这么大。 If you want to support bigger numbers, you'll have to use BigInt .
如果您想支持更大的数字,则必须使用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:因此,对于您的特定代码位,您需要做的就是将数字文字转换为 BigInt 文字,如下所示:
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 )这似乎给出了正确的结果(根据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:我可以收到 170:最大值:
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.