Reputation: 201
I wrote this simple code to generate 4th power of all positive integers up to 1005. It works fine only up to integer 215. After that it gives erroneous readings. why so?
# include<stdio.h>
int main(void)
{
int i;
unsigned long long int j;
for (i = 1; i <= 1005; i++){
j = i*i*i*i;
printf("%i.........%llu\n",i,j);
}
return 0;
}
Upvotes: 0
Views: 81
Reputation: 31952
You can fix it by making this small change.
unsigned long long i;
The problem is that in the line j = i*i*i*i;
, the right hand side is being calculated as an int
before it is being assigned to j
. Because of this if i^4
exceeds integer limits, it will basically start to go first negative and start cycling around when higher bits get clipped. When the negative number is assigned to j
, since j
is unsigned, -i
becomes max - i
, which is where the huge numbers come from. You will also need to change the printf
format specifier from %i
to %llu
for i
.
You can also fix this by doing the below
j = (unsigned long long)i*i*i*i;
This basically forces a cast up to the type of j
before performing the multiplication.
Sanity check - 215 ^4
= 2136750625 which is very close to the upper limit of signed int
of 2,147,483,647.
Upvotes: 5
Reputation: 62106
i*i
produces an int
. And so do i*i*i
and i*i*i*i
. 215 is the greatest positive integer whose 4th power fits into a 32-bit int
.
Beyond that the result is typically truncated (typically because strictly speaking you are having a case of undefined behavior; signed integer overflows result in UB per the C standard).
You may want to cast i
to unsigned long long
or define it as unsigned long long
, so the multiplications are 64-bit:
j = (unsigned long long)i*i*i*i;
Upvotes: 4