Yet another Fibonacci number generator First attempt at dynamic programming. I want to make this run faster and better.



fibonacci.cpp

#include "fibonacci.h"

std::map&lt;int, unsigned long long int&gt; initializeMap() {
    std::map&lt;int, unsigned long long int&gt; m;
    m[0] = 0;
    m[1] = 1;
    return m;
}

std::map&lt;int, unsigned long long int&gt; __fib_result_map = initializeMap();

unsigned long long int fibonacci(int seq) {
    using namespace std;
    map&lt;int, unsigned long long int&gt;&amp; m = __fib_result_map;
    if(m[seq] == 0 &amp;&amp; seq != 0) {
        m[seq] = fibonacci(seq - 2) + fibonacci(seq - 1);
    }
    return m[seq];
}




fibonacci.h

#ifndef __fibonacci
#define __fibonacci

#include &lt;iostream&gt;
#include &lt;map&gt;
#include &lt;vector&gt;
#include &lt;string&gt;
#include &lt;algorithm&gt;

unsigned long long int fibonacci(int seq);

#endif




fib_cpp.cpp

#include "fibonacci.h"
#include &lt;cstdlib&gt;
using namespace std;

int main(int argc, char* argv[]) {

    if(argc &lt;= 1) {
        cerr &lt;&lt; "No arguments specified. Usage: " &lt;&lt; argv[0] &lt;&lt; " &lt;values&gt;\n";
        return 1;
    }
    for(int i = 1; i &lt; argc; i++) {
        cout &lt;&lt; fibonacci(atoi(argv[i])) &lt;&lt; endl;
    }
    return 0;
}




Here is the repository on Github.
Assuming you're using the current c++ standard, since you don't specify in your question.


Prefer stoi to atoi. atoi has issues.
Prefer standard int types: std::uint128_t instead of unsigned long long int
Create a type alias for your map type since you use it a lot.
Don't include unnecessary headers in the fibbonacci.h file. Include them in the implementation.
It would make more sense to implement your memoizing map statically in the function.
You should use the map count method rather than relying on [] returning zero for a missing key


Putting these together

using fibmap = std::map&lt;int, std::uint128_t&gt;;

std::uint128_t fibonacci(int seq) {

    static fibmap m = {{0,0}, {0,1}};
    if (!m.count(seq)){
        m[seq] = fibonacci(seq - 2) + fibonacci(seq - 1);
    }
    return m[seq];
}