StackOverflowError computing factorial of a BigInteger?

后端 未结 5 1908
有刺的猬
有刺的猬 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:49

    The issue isn't BigInteger, it is your use of a recursive method call (getFactorial()).

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-01 18:57

    The Guava libraries from Google have a highly optimized implementation of factorial that outputs BigIntegers. Check it out. (It does more balanced multiplies and optimizes away simple shifts.)

    0 讨论(0)
  • 2020-12-01 19:09

    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!

    0 讨论(0)
  • 2020-12-01 19:09

    Naive implementations of factorial don't work out in real situations.

    If you have a serious need, the best thing to do is to write a gamma function (or ln(gamma) function) that will work not only for integers but is also correct for decimal numbers. Memoize results so you don't have to keep repeating calculations using a WeakHashMap and you're in business.

    0 讨论(0)
提交回复
热议问题