快速求幂运算
1 #include <stdio.h> 2 #include <math.h> 3 //递归算法 4 int recursion(int a,int b) 5 { 6 int tem = 1; 7 if(b==0)return 1; 8 else if(b==1)return a; 9 tem = recursion(a,b>>1); 10 tem = tem*tem; 11 if(b&1) tem = tem * a; 12 return tem; 13 } 14 //循环算法 15 int loop(int a,int b) 16 { 17 int tem=1,ret=a; 18 while(b>0) 19 { 20 if(b&1) tem = tem * ret; 21 ret = ret*ret; 22 b>>=1; 23 } 24 return tem; 25 } 26 int main() 27 { 28 int a,b; 29 while(1) 30 { 31 printf("For a^b input a and b:"); 32 scanf("%d%d",&a,&b); 33 printf("The recursion method:\n"); 34 printf("%d\n",recursion(a,b)); 35 printf("The loop method:\n"); 36 printf("%d\n",loop(a,b)); 37 } 38 return 0; 39 }
原理:
对应于递归算法,以下是算法依据:
直接乘要做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