快速幂算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include< iostream>
#include< stdio.h>
#define ll long long
using namespace std;
int kpow(ll a,ll b);
int main()
{
kpow(2,32);
}
int kpow(ll a,ll b)//int kpow(lla,llb,int c)
{
ll ans=1,base=a,temp=b;
while(b)
{
if(b&1!=0)#任何大于0的数除以2以后,最终都会为1
ans*=base;//ans=ans*base%c
base*=base;//base=(base*base)%c
cout<<base<<" "<<b<<endl;
b>>=1;
}
printf("%lld的%lld次方为:%lldn",a,temp,ans);
return ans;
}

快速幂本质上
upload successful,如果是取数取余数(中间结果取余相乘即可),见代码注释