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.
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))));
}
The maximum number the above program handles in 5022, after that the program throws a StackOverflowError
. Are there any other ways to handle it?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…