Philip Drach Philip Drach - 8 months ago 16
Java Question

How would I prevent my recursive Fibonacci sequence from generating a value past 4,000,000?

Here is my code:

public class EvenFibonacciNumbers {
//0 1 1 2 3 5 8 13 21 34
public static void main(String args[]){
int index = 0;
while (true){
public static long fibonacci(int i){ //i is our index value
//We will do this by recursion.
//We know that if our index is 0, it will return 0.
if(i == 0) return 0;
//We know that if our index is 1 or 2, it will return 1.
if (i <= 2) return 1;
//Now we need to determine what would happen if our index is greater
//than 2.
long fibTerm = fibonacci(i-1)+fibonacci(i-2);
return fibTerm;

What I think I have to do is change it to

while (fibTerm<4000000)

However, when I do this I get an error telling me that it cannot find the variable fibTerm. So, maybe this would be the wrong way to do this? I don't know exactly.


Add a local variable fibterm to store the last result of your calculation, check if the result exceeds your limit 4000000 and the print the result.

public static void main(String args[]){
    int index = 0;
    long fibterm = 0;
    while ((fibterm = fibonacci(index++)) < 4000000){