题解:P1226 【模板】快速幂
原理
有个显然的等式
那么我们把
也就是说我们只需要求出
而得到
我们可以在把
时间复杂度为
参考代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll qpow(ll a, ll b, ll p){
ll ans = 1;
for(;b;(a *= a) %= p, b >>= 1)if(b & 1)(ans *= a) %= p;
return ans;
}
int main(){
cin.tie(0)->sync_with_stdio(false);
int a, b, c;
cin >> a >> b >> c;
cout << a << "^" << b << " mod " << c << "=" << qpow(a, b, c);
return 0;
}