P1226 【模板】快速幂||取余运算
在计算$a*b\ \%\ p$和$a^{b}\ \%\ p$的时候,我们通常采用快速乘和快速幂来解决$long\ long$乘法溢出的问题
快速乘$a*b\ \%\ p$
1 ll qmul(ll a, ll b, ll p) { 2 ll res = 0; 3 while (b) { 4 if (b&1) res = (res+a)%p; 5 a = (a+a)%p; 6 b >>= 1; 7 } 8 return res%p; 9 }
快速幂$a^{b}\ \%\ p$
1 ll qpow(ll a, ll b, ll p) { 2 ll res = 1; 3 while (b) { 4 if (b&1) res = res*a%p; 5 a = a*a%p; 6 b >>= 1; 7 } 8 return res%p; 9 }
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 ll qmul(ll a, ll b, ll p) { 5 ll ans = 0; 6 while (b) { 7 if (b&1) ans = (ans+a)%p; 8 a = (a+a)%p; 9 b >>= 1; 10 } 11 return ans%p; 12 } 13 ll qpow(ll a, ll b, ll p) { 14 ll ans = 1; 15 while (b) { 16 if (b&1) ans = qmul(ans,a,p); 17 a = qmul(a,a,p); 18 b >>= 1; 19 } 20 return ans%p; 21 } 22 int main() { 23 ll b, p, k; scanf("%lld%lld%lld",&b,&p,&k); 24 ll s = qpow(b,p,k) % k; 25 printf("%lld^%lld mod %lld=%lld\n",b,p,k,s); 26 return 0; 27 }