在 Eclipse 中执行下面粘贴的代码时,大约有 3 次我遇到以下异常:
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)*
另外 2 次,它按预期吐出结果(每次运行之间的时间略有不同):
Recursive: 467946
Non Recursive: 61282
Difference between recursive and non-recursive: 406664
Sum from recursive add: 19534375
Sum from non-recursive add: 19534375
为什么异常只发生(似乎)〜30%的时间?
这是代码:
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;
}
}