Writing fibonacci sequence with a loop - Java

Viewed 25

I'm tasked with writing a method to calculate Fibonacci numbers iteratively. This is what I have so far:

public static long fibonacci (int n) {
    if (n <= 1 ) return n;
    
    int previous = 0;
    int current = 1;
    
    for (int i = 2; i <= n; i += 1) {
        int newFib = previous + current;
        previous = current;
        current = newFib;
    }
    return current;
    
}

My professor wrote a method to test our code with 13 different values of n. My code works for the first 6 tests getting the nth fibonacci number: fibonacci(0), fibonacci(1), fibonacci(2), fibonacci(3), 8, 13, and 25. However, when it reaches the 7th test, fibonacci(47), it fails and stops working for every test afterward: output of the failed tests

I've tried tweaking my for loop, but changing it causes every test to fail. I'm not sure why it stops working and I feel like I'm missing something simple. Any input would be appreciated.

1 Answers

Change the datatype from int to long

Related