Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci function doesn't calculate properly

I've defined this macro

#define FIB(n) (( 4 << n*(3+n))/((4 << (2*n)) - (2 << n) - 1))%(2 << n)

and when I try to get an answer, doesn't work properly, by example if I call FIB(7),it gives me 0, that clearly is wrong. I tested this function in python and it works perfectly. So, anyone can explain me why doesn't it work in C and C++?

like image 953
Natali Torres Avatar asked May 01 '16 08:05

Natali Torres


1 Answers

4 << n*(3+n) becomes 4 << 7*(3+7) when replace n with 7.

It means 4 << 70. If the size of int is 32 bits or 64 bits, shifting 70 bits is too much and this invokes undefined behavior in C.

Python supports multiple-precision arithmetic, so it may work well.

like image 90
MikeCAT Avatar answered Nov 14 '22 12:11

MikeCAT