Search code examples
c++algorithmdynamic-programmingfibonacci

Fibonacci memoization algorithm in C++


I'm struggling a bit with dynamic programming. To be more specific, implementing an algorithm for finding Fibonacci numbers of n.

I have a naive algorithm that works:

int fib(int n) {
    if(n <= 1)
        return n;
    return fib(n-1) + fib(n-2);
}

But when i try to do it with memoization the function always returns 0:

int fib_mem(int n) {
    if(lookup_table[n] == NIL) {
        if(n <= 1)
            lookup_table[n] = n;
        else
            lookup_table[n] = fib_mem(n-1) + fib_mem(n-2);
    }
    return lookup_table[n];
}

I've defined the lookup_table and initially stored NIL in all elements.

Any ideas what could be wrong?

Here's the whole program as requested:

#include <iostream>

#define NIL -1
#define MAX 100

long int lookup_table[MAX];

using namespace std;

int fib(int n);
int fib_mem(int n);

void initialize() {
    for(int i = 0; i < MAX; i++) {
        lookup_table[i] == NIL;
    }
}

int main() {
    int n;
    long int fibonnaci, fibonacci_mem;
    cin >> n;

    // naive solution
    fibonnaci = fib(n);

    // memoized solution
    initialize();
    fibonacci_mem = fib_mem(n);

    cout << fibonnaci << endl << fibonacci_mem << endl;

    return 0;
}

int fib(int n) {
    if(n <= 1)
        return n;
    return fib(n-1) + fib(n-2);
}

int fib_mem(int n) {
    if(lookup_table[n] == NIL) {
        if(n <= 1)
            lookup_table[n] = n;
        else
            lookup_table[n] = fib_mem(n-1) + fib_mem(n-2);
    }
    return lookup_table[n];
}

Solution

  • #include <iostream>
    #define N 100
    
    using namespace std;
    
    const int NIL = -1;
    int lookup_table[N];
    
    void init()
    {
        for(int i=0; i<N; i++)
            lookup_table[i] = NIL;
    }
    int fib_mem(int n) {
        if(lookup_table[n] == NIL) {
            if(n <= 1)
                lookup_table[n] = n;
            else
                lookup_table[n] = fib_mem(n-1) + fib_mem(n-2);
        }
        return lookup_table[n];
    }
    int main()
    {
        init();
        cout<<fib_mem(5);
        cout<<fib_mem(7);
    }
    

    Using the exactly same function, and this is working fine.

    You have done something wrong in initialisation of lookup_table.