basics · beginner · ~15 min
Iterative algorithms with two rolling variables.
Return the n-th Fibonacci number, where each term is the sum of the two before it.
Implement long fib(int n) returning the n-th Fibonacci number, defined by fib(0)=0, fib(1)=1, and fib(k)=fib(k-1)+fib(k-2) for k >= 2. No main — the grader calls it.
One int argument n with n >= 0.
The n-th Fibonacci number as a long.
fib(0) -> 0
fib(1) -> 1
fib(10) -> 55
fib(20) -> 6765
fib(0) is 0 and fib(1) is 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.
One int argument n with n >= 0.
The n-th Fibonacci number as a long (fib(0)=0, fib(1)=1).
Use an iterative O(n) loop, not naive recursion.
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.