Here is a recursive definition for the nth fibonacci term:
1 2 3
|
int fibonacci(std::size_t n) {
return (n < 2)? n: (fibonacci(n - 1) + fibonacci(n - 2));
}
|
Makes sense, hopefully?
The problem with this naive approach is that looking for the fourth term (
fibonacci(4)
), requires 5 calls to fibonacci(), a hell of a lot just to get 3 as the answer. Your computer is fast, but not that fast. You'll probably start feeling a delay around term 35; once you try for fibonacci(100), you'll be there for a Very Long Time waiting for all 708,449,696,358,523,830,148 recursive invocations to complete.
Line 5:
The vector is local to the function, which means that each recursive call gets its' own vector. Move it outside the function, or pass a reference to a vector into the function.
Line 7:
This is correct -- but line 8 isn't.
Each iteration, check to see if the value you are computing is in the vector. If it is, then simply return that. If it isn't, compute it, add it, and return the computed value.
The key point is that each function call needs access to the same vector.