Iterative Fibonacci algorithm giving me a wrong result after fib(47)

前端 未结 3 1932
旧巷少年郎
旧巷少年郎 2020-12-11 13:43

I am using the iterative fib algorithm that I have copied below. I have found this algorithm on Rosetta code and it gives me the correct answer up until fib(46). After that

3条回答
  •  旧时难觅i
    2020-12-11 14:12

    Notice that you are using temporary variables of type int in your code rather than type long long int. This means that if you get to the point where you're dealing with sufficiently large Fibonacci numbers, you'll get an integer overflow in your code. In particular, the 47th Fibonacci number is 2,971,215,073, which is too large to fit in a signed 32-bit integer, so you'll get an overflow.

    Changing your temporary variables to type long long int (or, better yet, uint64_t) should fix this.

提交回复
热议问题