int pow3(int x, int n)
{
intresult = 1;
while(n > 0) {
if(n & 1) // n & 1 等价于 (n % 2) == 1
result *= x;
x*= x;
n>>= 1; // n >>= 1 等价于 n /= 2
}
returnresult;
}
NumberTypeoptimized_pow_n(NumberType x, unsigned int n)
{
NumberType pw = 1;
while (n > 0){
if (n &1) // n & 1 等价于 (n % 2) == 1
pw *= x;
x *= x;
n >>=1; // n >>= 1 等价于 n /= 2
}
return pw;
}
#include <stdio.h>
#include<math.h>
//递归算法
intrecursion(int a,int b)
{
inttem = 1;
if(b==0)return 1;
elseif(b==1)return a;
tem =recursion(a,b>>1);
tem =tem*tem;
if(b&1) tem = tem * a;
returntem;
}
//循环算法
intloop(int a,int b)
{
inttem=1,ret=a;
while(b>0)
{
if(b&1) tem = tem * ret;
ret = ret*ret;
b>>=1;
}
returntem;
}
int main()
{
inta,b;
while(1)
{
printf("For a^b input a and b:");
scanf("%d%d",&a,&b);
printf("Therecursion method:\n");
printf("%d\n",recursion(a,b));
printf("The loop method:\n");
printf("%d\n",loop(a,b));
}
return0;
}
原理:
直接乘要做998次乘法。但事实上可以这样做,先求出2^k次幂:
3 ^ 2 = 3 * 3
3 ^ 4 = (3 ^ 2) * (3 ^ 2)
3 ^ 8 = (3 ^ 4) * (3 ^ 4)
3 ^ 16 = (3 ^ 8) * (3 ^ 8)
3 ^ 32 = (3 ^ 16) * (3 ^ 16)
3 ^ 64 = (3 ^ 32) * (3 ^ 32)
3 ^ 128 = (3 ^ 64) * (3 ^ 64)
3 ^ 256 = (3 ^ 128) * (3 ^ 128)
3 ^ 512 = (3 ^ 256) * (3 ^ 256)
再相乘:
3 ^ 999
= 3 ^ (512 + 256 + 128 + 64 + 32 + 4 + 2 + 1)
= (3 ^ 512) * (3 ^ 256) * (3 ^ 128) * (3 ^ 64) * (3 ^ 32) * (3 ^ 4) * (3 ^ 2) *3