Arm Mbed and Pelion Device Management support forum

Integer overflow

Hi, I am trying to code the function as f(2n+1)=f(n)+f(n-1) ( for odd input) and f(2n)=f(n) (for even numbers) in a recursive function. The problem I have is that for large numbers e.g.123456789012345678, there is no answer which is due to integer overflow. But I could not find a solution for it. I appreciate any help. Thanks

Hi @mmdparsi
I would not recommend using recursive calls for such functions, especially not on embedded systems. In addition to integer overflow, you would get stack overflows.
As for integer overflow, have you considered changing 64 bit unsigned integers? Assuming, your functions should handle positive numbers only, of course, the biggest value that can be handled is 2^64.
If this is not enough, there are several libraries out there, such as Mbed TLS, that have bignum modules, and can handle big integers.
However, in order to avoid the integer overflow, I would check boundary that input does not exceed MAX_INT and if it does, return an error
Regards,
Mbed Support
Ron