StackOverflowError计算BigInteger的阶乘?

Vin*_*C M 14 java stack-overflow algorithm biginteger factorial

我正在尝试编写一个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))));
  }
Run Code Online (Sandbox Code Playgroud)

上述程序在5022中处理的最大数量,之后程序抛出一个StackOverflowError.有没有其他方法来处理它?

tem*_*def 28

这里的问题看起来像是来自过多递归堆栈溢出(5000个递归调用看起来像关于吹出Java 调用堆栈的正确调用次数)而不是限制.迭代地重写阶乘函数应该解决这个问题.例如: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;
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!