Compiler is g++ 4.2. I’m new to C++, but I’ve done a lot of data science, web scraping, and some socketing stuff in Python. This code generates the nth Fibonacci number, either with a naive implementation or with caching.
#include <iostream>
#include <string>
#include <unordered_map>
#define BIG unsigned long long int
std::unordered_map<int, BIG> umap;
int fib(int n) {
if (n < 2) {
return n;
}
return fib(n-1) + fib(n-2);
}
BIG fib_with_memo(int n) {
if (umap.find(n) == umap.end()) { // if F_n not in cache, calculate, cache, and return it
BIG val = fib_with_memo(n-1) + fib_with_memo(n-2);
umap(n) = val;
return val;
}
return umap(n); // otherwise return the cached value
}
int main(int argc, char** argv) {
umap(0) = 0;
umap(1) = 1;
int input = std::stoi( std::string(argv(1)) );
std::cout << fib_with_memo(input) << std::endl;
return 0;
}
I used a std::unordered_map
(hash table) because its lookup/insertion times are $O(1)$ (compared to the std::map
, which has $O(log(n))$ for both.)