So I have the following code:
#include <stdio.h>
unsigned long int fibonacci()
{
static int count = -1;
static int f1 = 0;
static int f2 = 1;
count++;
if(count == 0 || count == 1) {
return count;
} else {
int f3 = f1 + f2;
f1 = f2;
f2 = f3;
return f3;
}
}
int main()
{
int i;
for(i = 1; i <= 50; i++) {
printf("\n%i: %li", i, fibonacci());
}
return 0;
}
For the 48th fibonacci number, the output is -1323752223
indicating that the initial number was too large for the data type of the variable. The 48th fibonacci number is 2971215073
but google says the data type long int
can handle numbers up to over 4 billion. So why can't it handle a number barely under 3 billion?
A long
is a signed type and it must be large enough to at least handle the values -231-1 to 231-1.
Since C nowadays uses two's complement only, that means that the value range must at least be -2147483648 to 2147483647.
but google says the data type long int can handle numbers up to over 4 billion
No, that's an unsigned long
which can handle values up to at least 232-1 = 4.29 billion.
Notably, most ABI specify long
as 32 bits but a few specify it as 64 bits. Why it is a non-portable type and we are much better off using the portable types int32_t
or int64_t
.