学习代码
详情请见:快速幂_百度百科 http://baike.baidu.com/view/4533005.htm
//普通求幂
template<typename T>
T pow1(T num, T n)
{
T r = 1;
while (n--)
r *= num;
return r;
}
//二分求幂(一般)
template<typename T>
T pow2(T num, T n)
{
T r = 1;
T base = num;
while (n)
{
if (n % 2)
r *= base;
base *= base;
n /= 2;
}
return r;
}
//二分求幂(位运算)
template<typename T>
T pow3(T num, T n)
{
T r = 1;
T base = num;
while (n != 0)
{
if (n & 1)
r *= base;
base *= base;
n >>= 1;
}
return r;
}
//二分求幂(更复杂的位运算)
template<typename T>
T pow4(T num, T n)
{
if (n == 0)
return 1;
else
{
while ((n & 1) == 0)
{
n >>= 1;
num *= num;
}
}
int result = num;
n >>= 1;
while (n)
{
num *= num;
if (n & 1)
{
result *= num;
}
n >>= 1;
}
return result;
}