The problem
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 possible solution
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!
More efficient solutions
There are faster algorithms than this. See another question and its links for more details.