Note that there are some explanatory texts on larger screens.

plurals
  1. POOccasional StackOverflowError in Recursive Calculation
    primarykey
    data
    text
    <p>When executing the code pasted below in Eclipse, approximately 1 out of 3 times I encounter the following exception:</p> <pre><code>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)* </code></pre> <p>The other 2 times, it spits out the result as intended (the times vary slightly between each run):</p> <pre><code>Recursive: 467946 Non Recursive: 61282 Difference between recursive and non-recursive: 406664 Sum from recursive add: 19534375 Sum from non-recursive add: 19534375 </code></pre> <p>Why does the exception only happen (seemingly) ~30% of the time?</p> <p>Here's the code:</p> <pre><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 &lt;= i; num++) { count += num; } return count; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload