0

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?

Kashif
  • 3,063
  • 6
  • 29
  • 45
  • 1
    It looks like fibo(300) would be `222232244629420445529739893461909967206666939096499764990979600` according to [this](http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html). Log base 2 of that number is right around `207`, so a 64 bit `long long` isn't quite going to cut it... – scohe001 Apr 22 '19 at 16:04
  • You need long ariphmetics for this task. – trollingchar Apr 22 '19 at 16:04
  • 1
    Take a look at [GMP](https://gmplib.org) (or other similar libraries) if you need to work with numbers larger than what the native C++ types support. – Jesper Juhl Apr 22 '19 at 16:06

0 Answers0