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;
}
You can fix it by making this small change.
The problem is that in the line
j = i*i*i*i;, the right hand side is being calculated as anintbefore it is being assigned toj. Because of this ifi^4exceeds 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 toj, sincejis unsigned,-ibecomesmax - i, which is where the huge numbers come from. You will also need to change theprintfformat specifier from%ito%llufori.You can also fix this by doing the below
This basically forces a cast up to the type of
jbefore performing the multiplication.Sanity check –
215 ^4= 2136750625 which is very close to the upper limit ofsigned intof 2,147,483,647.