First attempt at dynamic programming. I want to make this run faster and better.
fibonacci.cpp
#include "fibonacci.h"
std::map<int, unsigned long long int> initializeMap() {
std::map<int, unsigned long long int> m;
m[0] = 0;
m[1] = 1;
return m;
}
std::map<int, unsigned long long int> __fib_result_map = initializeMap();
unsigned long long int fibonacci(int seq) {
using namespace std;
map<int, unsigned long long int>& m = __fib_result_map;
if(m[seq] == 0 && seq != 0) {
m[seq] = fibonacci(seq - 2) + fibonacci(seq - 1);
}
return m[seq];
}
fibonacci.h
#ifndef __fibonacci
#define __fibonacci
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
unsigned long long int fibonacci(int seq);
#endif
fib_cpp.cpp
#include "fibonacci.h"
#include <cstdlib>
using namespace std;
int main(int argc, char* argv[]) {
if(argc <= 1) {
cerr << "No arguments specified. Usage: " << argv[0] << " <values>\n";
return 1;
}
for(int i = 1; i < argc; i++) {
cout << fibonacci(atoi(argv[i])) << endl;
}
return 0;
}
Here is the repository on Github.