DEV Community

Discussion on: Fibonacci: Recursion vs Iteration

Collapse
 
misterpoloy profile image
Juan P. Ortiz

Your iterative solution is wrong, does not work for any number.
onlinegdb.com/HyqiFsZY8

In this case, we manually handle cases for 1 and 2 and start the loop from 2:

int getNthFib(int n) {
    if (n == 1) return 0;
    if (n == 2) return 1;
    int prevPrev = 0;
    int prev = 1;
    int currentNumber;
    for (int i = 2; i < n; i++) {
        currentNumber = prevPrev + prev;
        prevPrev = prev;
        prev = currentNumber;
    } 
    return currentNumber;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
risingh1981 profile image
risingh1981

Minor error: You are using 0 for the first Fib #, but F(0) = 0 and F(1) = 1

Collapse
 
ashrav profile image
ashrav

"i" should start with 1, or it should continue till <= n;