I've implemented Fibonacci Series with memoization using dictionary in Python.
def fib(n, my_dict={}):
if n in my_dict:
return my_dict[n]
if n<=2:
return 1
my_dict[n] = fib(n-1, my_dict) + fib(n-2, my_dict)
return my_dict[n]
print(fib(50))
I've tried to create an equivalent in C++ it's working fine till 46 but giving strange output after 46. I've provided the code below.
#include<iostream>
#include<unordered_map>
using std::unordered_map;
using std::cout;
int fib(int num, unordered_map <int, int> &Dict)
{
if (Dict.find(num) != Dict.end())
{
return Dict[num];
}
if (num <= 2)
{
return 1;
}
Dict[num] = fib(num-1, Dict) + fib(num-2, Dict);
return Dict[num];
}
int main()
{
int n;
cout<<"Enter the number: ";
std::cin>>n;
unordered_map <int, int> Dict;
cout<<fib(n, Dict);
return 0;
}