的StackOverflowError计算BigInteger的阶乘? [英] StackOverflowError computing factorial of a BigInteger?
问题描述
我想写一个Java程序来计算大量的阶乘。这似乎的BigInteger
无法容纳这么大的数字。
I am trying to write a Java program to calculate factorial of a large number. It seems BigInteger
is not able to hold such a large number.
下面是(简单的)code我写的。
The below is the (straightforward) code I wrote.
public static BigInteger getFactorial(BigInteger num) {
if (num.intValue() == 0) return BigInteger.valueOf(1);
if (num.intValue() == 1) return BigInteger.valueOf(1);
return num.multiply(getFactorial(num.subtract(BigInteger.valueOf(1))));
}
在5022以上程序处理,之后,该计划抛出一个的StackOverflowError
的最大数量。是否有任何其他的方式来处理呢?
The maximum number the above program handles in 5022, after that the program throws a StackOverflowError
. Are there any other ways to handle it?
推荐答案
这里的问题看起来像它的一个堆栈溢出从过多递归(5000递归调用看起来像有关呼叫权数吹出一个Java < A HREF =http://en.wikipedia.org/wiki/Call_stack>调用堆栈),而不是的BigInteger
。反复重写阶乘函数应该解决这个问题。例如:
The problem here looks like its a stack overflow from too much recursion (5000 recursive calls looks like about the right number of calls to blow out a Java call stack) and not a limitation of BigInteger
. Rewriting the factorial function iteratively should fix this. For example:
public static BigInteger factorial(BigInteger n) {
BigInteger result = BigInteger.ONE;
while (!n.equals(BigInteger.ZERO)) {
result = result.multiply(n);
n = n.subtract(BigInteger.ONE);
}
return result;
}
希望这有助于!
Hope this helps!
这篇关于的StackOverflowError计算BigInteger的阶乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!