I have the following power function that works with integers and 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 would like to have a version that allows exp> 32. Therefore, 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 does not work:
unsigned long long int x;
x = ipow( 2, 35 );
printf( "%llu\n", x );
this will exit 0.
What is the problem with my unsigned long int implementation?
source
share