This is a simple recursive method with caching so that the numbers will not get recalculated over and over again. I've definitely seen it work, but now it's broken and prints rubbish. I've tried reverting to working version, but just can't find any difference that could have broken it.
Why did it stop working?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int Fibonacci_vector(int n) {
static vector<int> cache(2, 1);
cache.reserve(n);
if (cache[n] == 0) {
cache[n] = Fibonacci_vector(n-1) + Fibonacci_vector(n-2);
}
return cache[n];
}
int main() {
cout << Fibonacci_vector(4);
}
UPDATE Jeez, I'm so stupid that it just hurts. I've changed if (n > cache.size()) { cache.resize(n); }
to cache.reserve(n);
and of course it broke everything! So sorry for my stupidity, guys.