I've been working around with this recursive function
but couldn't find myself which led me to overflow error
and it keeps coming around. I've already tried casting to BigInteger
also but nothing special is coming. I don't see any warning or syntax error in my Eclipse IDE
. I had to submit an efficient algorithm for big numbers. thanks in advance. :-)
public static BigInteger factorial(int n)
{
return n > 2 ? new BigInteger(n+"").multiply(factorial(n-1)) : new BigInteger(n+"");
}
You're getting the error because the computer has to remember every method call you make (and other information) until that method call is finished, and there's only so much space on the "stack" set aside to remember all that.
You recurse so many times that you overflow the stack space set up to remember method calls that are in progress. That's called a stack overflow.
A reasonably-efficient algorithm is to use a simple loop. This has the side benefit of not causing stack overflows, since you don't create more method calls over and over again, you just do stuff inside the first method call.
You should also use BigInteger.valueOf(n)
instead of new BigInteger(n+"")
:
public static BigInteger factorial(int n) {
BigInteger result = BigInteger.ONE;
for (; n > 1; n--) {
result = result.multiply(BigInteger.valueOf(n));
}
return result;
}
This takes my computer about 6 seconds to compute 100,000!
There are faster algorithms than this. See another question and its links for more details.