我有一个作用于整数的幂函数,它运作正常:
int ipow( int base, int exp )
{
int result = 1;
while( exp )
{
if ( exp & 1 )
{
result *= base;
}
exp >>= 1;
base *= base;
}
return result;
}
现在我希望有一个允许 exp > 32 的版本。因此,我使用了 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;
}
但是这个第二个版本似乎不起作用:
unsigned long long int x;
x = ipow( 2, 35 );
printf( "%llu\n", x );
这将输出0。
我的unsigned long long int实现有什么问题?