When executing the code pasted below in Eclipse, approximately 1 out of 3 times I encounter the following exception:
Exception in thread "main" java.lang.StackOverflowError
at src.Adder.recursiveSumAllNumbersUpTo(Driver.java:33)
at src.Adder.recursiveSumAllNumbersUpTo(Driver.java:37)
... *(there are 1024 lines in this stack)*
The other 2 times, it spits out the result as intended (the times vary slightly between each run):
Recursive: 467946
Non Recursive: 61282
Difference between recursive and non-recursive: 406664
Sum from recursive add: 19534375
Sum from non-recursive add: 19534375
Why does the exception only happen (seemingly) ~30% of the time?
Here's the code:
public class Driver {
public static void main(String[] args) {
Adder adder = new Adder();
int valueToSumTo = 6250;
long startTime = System.nanoTime();
int raSum = adder.recursiveAddAllNumbersUpTo(valueToSumTo);
long endTime = System.nanoTime();
long raDif = endTime - startTime;
System.out.println("Recursive: " + (raDif));
startTime = System.nanoTime();
int nonRaSum = adder.nonRecursiveAddAllNumbersUpTo(valueToSumTo);
endTime = System.nanoTime();
long nonRaDif = endTime - startTime;
System.out.println("Non Recursive: " + (nonRaDif));
System.out.println("Difference between recursive and non-recursive: " + (raDif - nonRaDif));
System.out.println("Sum from recursive add: " + raSum);
System.out.println("Sum from non-recursive add: " + nonRaSum);
}
}
class Adder {
public int recursiveAddAllNumbersUpTo(int i) {
if (i == 1) {
return i;
}
return i + recursiveAddAllNumbersUpTo(i - 1);
}
public int nonRecursiveAddAllNumbersUpTo(int i) {
int count = 0;
for(int num = 1; num <= i; num++) {
count += num;
}
return count;
}
}
Everytime a recursive method calls itself, everything goes to the stack and algorithm such as yours requires a very deep stack.
To solve your problem, you should increase your Stack Size.
You can do that by calling the JVM with the -Xss parameter.
If you are using Eclipse you can do that by doing the following:
Try a bigger stack if that configuration is not enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With