快速幂!
模板如下:
#include<iostream> #include<cmath> #include<cstdio> #define LL long long using namespace std; LL b,p,k; LL fastpow(LL a,LL b) { LL r=1; LL base=a; while(b!=0) { if(b%2!=0)//奇次幂 r=r*base; base=base*base; b=b/2; } return r; } LL fff(LL n,LL m) { if(m == 0) return 1; LL t = fff(n,m /2); t = 1LL * t * t % k; if(m&1) t = 1LL * t * n % k; return t; } LL mod_exp(LL a, LL b, LL c) //快速幂取余a^b%c { LL res,t; res=1%c; t=a%c; while(b) { if(b&1) { res=res*t%c; } t=t*t%c; b>>=1;//就等价于b/2(位运算) } return res; } int main() { scanf("%lld%lld%lld",&b,&p,&k); LL tmpb=b; b%=k;//防止b太大 /* start 快速幂求得b^p */ cout<<tmpb<<"^"<<p<<"="<<fastpow(b,p)<<endl; /* end 快速幂求得b^p */ /* start 快速幂求得b^p%k */ cout<<tmpb<<"^"<<p<<" mod "<<k<<"="<<mod_exp(b,p,k)<<endl; /* 方法一 end */ cout<<tmpb<<"^"<<p<<" mod "<<k<<"="<<fff(b,p)<<endl; /* 方法二 end */ /* end 快速幂求得b^p%k */ return 0; }