I have the following power function which operates on integers and it works fine:
int ipow( int base, int exp )
{
int result = 1;
while( exp )
{
if ( exp & 1 )
{
result *= base;
}
exp >>= 1;
base *= base;
}
return result;
}
Now I'd like to have a version which allows exp > 32. So I use unsigned long long ints:
unsigned long long int ipow( int base, int exp )
{
unsigned long long int result = 1ULL;
while( exp )
{
if ( exp & 1 )
{
result *= (unsigned long long int)base;
}
exp >>= 1;
base *= base;
}
return result;
}
But this second version doesn't seem to work:
unsigned long long int x;
x = ipow( 2, 35 );
printf( "%llu\n", x );
this will output 0.
What's the problem with my unsigned long long int implementation?
Description. Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).
They are the same type.
Assuming 4 bytes, a long has the range of -2,147,483,648 to 2,147,483,647 . An unsigned long has the range of 0 to 4,294,967,295 .
In 32-bit mode, the compiler (more precisely the <stdint. h> header) defines uint64_t as unsigned long long , because unsigned long isn't wide enough. In 64-bit mode, it defines uint64_t as unsigned long . It could have defined it as unsigned long long in both modes.
Your base
variable is too small. Change it to unsigned long long int
, like the others, since it holds numbers greater than 2^32
.
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