Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing fibonacci sequence with a loop – Java

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Change the datatype from int to long

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading