#include #include #include using namespace std; class Fib { // Step four: removing (or minimizing) the cache. public: long long find_fib(int n); }; long long Fib::find_fib(int n) { vector cache; int i; if (n == 0 || n == 1) return 1; /* The key observation here is that we only need the last two entries of the cache. So, we'll limit the cache to two entries. We'll keep the odd ones in cache[0], and the even ones in cache[1]. */ cache.resize(2, 1); for (i = 2; i <= n; i++) { cache[i%2] = cache[0] + cache[1]; } /* Return cache[0] if n is even, and cache[1] if n is odd. */ return cache[n%2]; } int main(int argc, char **argv) { Fib f; if (argc != 2) { cerr << "usage: fib n\n"; exit(1); } cout << f.find_fib(atoi(argv[1])) << endl; return 0; }