StackOverflowError computing factorial of a BigInteger?

后端 未结 5 1928
有刺的猬
有刺的猬 2020-12-01 18:33

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

5条回答
  •  独厮守ぢ
    2020-12-01 18:52

    Try this instead, an iterative algorithm:

    public static BigInteger getFactorial(int num) {
        BigInteger fact = BigInteger.valueOf(1);
        for (int i = 1; i <= num; i++)
            fact = fact.multiply(BigInteger.valueOf(i));
        return fact;
    }
    

提交回复
热议问题