I was originally solving the Project Euler problem #2 which computes even numbers of the fibonacci sequence up to 4,000,000. I completed this and then I wanted to increase the maximum number so that it would continue infinitely, producing results more slowing as it took longer to compute.
I got a Stack Overflow Error and wondered if there was an alternative solution for the code so that it would be able to continue running, albeit slowly, without encountering a stack overflow error.
Can someone please provide assistance in refactoring my solution? Thanks.
The relevant code for this problem has been provided below.
public static void main(String[] args) {
fibonacci(1,2,2);
}
private static void fibonacci(long first, long second, long sum) {
long number = first + second;
if (number % 2 == 0){ //Checks for even number
sum = sum + number;
}
System.out.println(sum);
fibonacci(second, number, sum);
// Produces the following error:
// Exception in thread "main" java.lang.StackOverflowError
}