快速幂的两种写法
1: //非递归版本
2: //输入a,b; 求解a^b
3: #include<iostream>
4: #include<cstdio>
5: using namespace std;
6:
7: int main(){
8: int a,b;
9: //ans:最终结果
10: //count:while 循环执行的次数
11: scanf("%d%d",&a,&b);
12: int count=0,ans,tpans;
13: ans=1; tpans=a;
14: while (b){
15: ++count;
16: if (b&1) ans*=tpans;
17: tpans=tpans*tpans; b>>=1;
18: }
19: printf("Count=%d\na^b=%d\n",count,ans);
20: return 0;
21: }
递归版本快速幂
1: //输入a,b,求解a^b
2: #include <iostream>
3: #include <cstdio>
4: //power(a,b) 返回a^b
5: int power(int a,int b){
6: if(b==1)return a;
7: int tpans=power(a,b>>1);
8: return tpans*tpans*((b&1)?a:1);
9: }
10: int main(){
11: int a,b;
12: scanf("%d%d",&a,&b);
13: printf("a^b=%d\n",power(a,b));
14: return 0;
15: }