c - Iterative Fibonacci algorithm giving me a wrong result after fib(47) -
i using iterative fib algorithm have copied below. have found algorithm on rosetta code , gives me correct answer until fib(46). after values wrong. know why case?
long long fibb(int n) { int fnow = 0, fnext = 1, tempf; while(--n > 0) { tempf = fnow + fnext; fnow = fnext; fnext = tempf; } return fnext; }
output:
fib(46) = 1836311903 <---- correct fib(47) = 18446744092385799393 <---- wrong (correct answer is: 2971215073)
notice using temporary variables of type int
in code rather type long long int
. means if point you're dealing sufficiently large fibonacci numbers, you'll integer overflow in code. in particular, 47th fibonacci number 2,971,215,073, large fit in signed 32-bit integer, you'll overflow.
changing temporary variables type long long int
(or, better yet, uint64_t
) should fix this.
Comments
Post a Comment