basics · beginner · ~15 min
Iterative algorithms with two rolling variables.
Implement long fib(int n) returning the n-th Fibonacci number where fib(0)=0, fib(1)=1.
Fibonacci is the canonical recursive vs iterative comparison. The recursive version takes O(2^n); the iterative version is O(n). It's a great way to feel the difference.
long fib(int n) {
/* TODO */
return 0;
}
Using naive recursion for large n (it takes forever). Starting from F(0)=0 vs F(1)=1 inconsistently. Overflowing int at F(47).
F(0) = 0, F(1) = 1 (definition). F(47) overflows int.
O(n) iterative. O(phi^n) ≈ O(1.618^n) naive recursive.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.