I wrote a Java recursive method that calculates the summation of n from 0 to n. Here's the code:
private static long sum (long n) {
if (n == 0) {
return 0;
} else {
return n + sum(n-1);
}
}
When I pass a large number such as 11000 and above, a stack overflow happens sometimes. Yes, I said sometimes. When n is greater than or equals to 11000 the program runs and either gives me the answer or a stack overflow.
Can anyone explain what's going on?