#include #include #include using namespace std; class Fib { // This is step three -- remove the recursion and build the cache. public: long long find_fib(int n); vector cache; }; long long Fib::find_fib(int n) { int i; if (n == 0 || n == 1) return 1; cache.resize(n+1, -1); /* Because all of our recursive calls were to smaller values of n, we can build the cache from small to big. */ cache[0] = 1; cache[1] = 1; for (i = 2; i <= n; i++) cache[i] = cache[i-1] + cache[i-2]; return cache[n]; } 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; }