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++?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With