HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

Yet another Fibonacci number generator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numberfibonaccigeneratoryetanother

Problem

First attempt at dynamic programming. I want to make this run faster and better.

fibonacci.cpp

#include "fibonacci.h"

std::map initializeMap() {
    std::map m;
    m[0] = 0;
    m[1] = 1;
    return m;
}

std::map __fib_result_map = initializeMap();

unsigned long long int fibonacci(int seq) {
    using namespace std;
    map& 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 
#include 
#include 
#include 
#include 

unsigned long long int fibonacci(int seq);

#endif


fib_cpp.cpp

#include "fibonacci.h"
#include 
using namespace std;

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

    if(argc \n";
        return 1;
    }
    for(int i = 1; i < argc; i++) {
        cout << fibonacci(atoi(argv[i])) << endl;
    }
    return 0;
}


Here is the repository on Github.

Solution

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;

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];
}

Code Snippets

using fibmap = std::map<int, std::uint128_t>;

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];
}

Context

StackExchange Code Review Q#139888, answer score: 12

Revisions (0)

No revisions yet.