I’m a newcomer to c++ trying to pick up the ropes, i was trying to write a recursive and memoized fibonacci function that returns the nth fibonacci number, i want to use std::map for the memoization, i also wrote a python version that does the same thing. the problem is that at the number 94, the c++ version of the program returns the wrong value but up until that point it was working well, could anyone point me in the right direction?
#include <iostream>
#include <map>
#define Log(x) std::cout << x << std::endl;
unsigned long long int fib(const int &n)
{
static std::map<int, unsigned long long int> memo;
if (n < 3)
return 1;
if (memo.count(n) > 0)
return memo[n];
memo[n] = fib(n - 1) + fib(n - 2);
return memo[n];
}
int main(int argc, const char *argv[])
{
int number;
std::cout << "Enter a number: ";
std::cin >> number;
Log(fib(number));
}
here is the python version which works fine,
import sys
def fib(n, memo={}):
if n < 3:
return 1
if n in memo:
return memo[n]
memo[n] = fib(n - 1) + fib(n - 2)
return memo[n]
sys.setrecursionlimit(10**7)
number = int(input("Enter a number: "))
print(fib(number))
here is the output:
$ ./executables/fib
Enter a number: 93
12200160415121876738
$ python ./fib.py
Enter a number: 93
12200160415121876738
$ ./executables/fib
Enter a number: 94
1293530146158671551
$ python ./fib.py
Enter a number: 94
19740274219868223167
Any help would be highly appreciated