我有對整數經營以下冪函數,它工作正常:無符號長long int類型戰俘
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類型長整型:
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實現有什麼問題?
確實,非常感謝,現在就工作! – DanielFetchinson 2013-03-05 13:53:13