data-structures · beginner · ~15 min
Compute Fibonacci in O(n) with a rolling pair, not exponential recursion.
Implement:
long long fib(int n);
Return the n-th Fibonacci number (fib(0)=0, fib(1)=1). Build the answer bottom-up. 0 <= n <= 90.
n in [0,90].
The n-th Fibonacci number.
Use long long; fib(90) overflows 32 bits.
#include <stddef.h>
/* Return the n-th Fibonacci number (fib(0)=0, fib(1)=1). 0<=n<=90. */
long long fib(int n){ (void)n; return 0; }
Naive recursion is exponential; recompute nothing — keep two rolling values.
fib(0)=0, fib(1)=1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.