Each term is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13 ...
Formula: F(n) = F(n-1) + F(n-2), F(0) = 0, F(1) = 1
int n = 10, a = 0, b = 1;
for(int i = 0; i < n; i++){
cout << a << " ";
int next = a + b;
a = b;
b = next;
}
// 0 1 1 2 3 5 8 13 21 34
int fib(int n){
if(n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
long long memo[100];
long long fib(int n){
if(n <= 1) return n;
if(memo[n]) return memo[n];
return memo[n] = fib(n - 1) + fib(n - 2);
}
Q & A
-
Why is plain recursive Fibonacci slow?The same values are computed again and again, so the calls grow like 2^n. Memoization stores each answer once and makes it O(n).