我正在尝试编写一个 Java 程序来计算大数的阶乘。看来 BigInteger
无法容纳这么大的数字。
下面是我写的(简单的)代码。
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
。有没有其他办法处理?
最佳答案
这里的问题看起来像一个 stack overflow来自太多recursion (5000 次递归调用看起来大约是使 Java 崩溃的正确调用次数 call stack )而不是 BigInteger
的限制。迭代重写阶乘函数应该可以解决这个问题。例如:
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;
}
希望这对您有所帮助!
关于java - StackOverflowError 计算 BigInteger 的阶乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8992437/