快速幂取模,即求a的n次方再取模,如果n很大,时间开销会很大
其原理是以下两个明显的公式:
代码如下:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MOD=1000009;
LL powerMod(LL a,LL n){
LL res=1;
while(n){
if(n%2)
res=res*a%MOD;
n/=2;
a=a*a%MOD;
}
return res;
}
int main(){
LL a,n;
while(cin>>a>>n){
LL res=powerMod(a,n);
cout<<res<<endl;
}
return 0;
}
时间复杂度为O(logn)。