I wrote up a C++ program to compute the nth Fibonacci number. I noticed that it wouldn't return the correct numbers for large n. In Python, my code runs perfectly, albeit slower.
I think there are issues with handling big integers in C++ and I don't see why that would be the case when I declared n, current, and previous to be long long.
#include <iostream>
int fibonacci(long long n) {
if (n <= 1)
return n;
long long previous = 0;
long long current = 1;
for (long long i = 0; i < n - 1; ++i) {
long long tmp_previous = previous;
previous = current;
current = tmp_previous + current;
}
return current;
}
int main() {
long long n = 0;
std::cin >> n;
std::cout << fibonacci(n);
}
When I evaluate this at n=300, I get -1287770608. This isn't right at all. Anyone have ideas how to fix this?