快速幂模版
核心思想:
每一步都把指数分成两半,而相应的底数做平方运算,最后求出的幂结果实际上就是在变化过程中所有当指数为奇数时底数的乘积。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a,b,p;
ll ksm(ll x,ll y){
ll res=1;
while(y){
if(y&1){//当指数为奇数时
res=res*x%p;
}
y>>=1;//指数缩为一半
x=x*x%p;
}
return res;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin>>a>>b>>p;
cout<<a<<"^"<<b<<" mod "<<p<<"="<<ksm(a,b);
return 0;
}

浙公网安备 33010602011771号