Not entirely sure if I implemented it correctly, but I tried to use memoization for this fib programme and it turns out to be slower than if I just ran it without,
does anyone know why this is happening?
~Finding the 39th value in the sequence.
*Results without Map (Memoization):
39
63245986
Time taken by program is : 1.000000 sec
*Results with Map:
39
63245986
Time taken by program is : 35.000000 sec
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int fibNum(int n) {
map <int, int> mp = {};
if(mp.find(n) != mp.end()){
return mp[n];
} else
/* Remove this top part for non-map way*/
if (n == 1 || n == 2){
return 1;
} else if (n == 0){
return 0;
} else {
int answer = fibNum(n - 1) + fibNum(n - 2);
mp[n] = answer;
/* Remove this part about assigning value to the key*/
return answer;
}
return 0;
}
/*Running the Fibonnac Programme, main programme is above*/
int main() {
int term; cin >> term;
time_t start,end;
time(&start);
ios_base::sync_with_stdio(false);
cout << fibNum(term) << endl;
time(&end);
double timeTaken = double(end - start);
cout << "Time taken by program is : " << fixed
<< timeTaken << ' ' << " sec\n";
return 0;
}

In your
fibNumfunction you're creating an empty map on each call and then doing a lookup in it. You need to use the map by looking upnin the map before resorting to the recursive callsfibNum(n - 1)andfibNum(n - 2)and you need to pass the map to the function as a reference parameter so the map can be built up and store the found numbers.