题意
求 a b m o d m a^b\ mod\ m ab mod m
思路
因为
b
b
b很大所以不能直接算,这要用到扩展欧拉定理:
当
a
,
m
∈
Z
a, m \in \mathbb{Z}
a,m∈Z时有:
a
b
≡
{
a
b
,
b
<
φ
(
m
)
a
b
m
o
d
φ
(
m
)
+
φ
(
m
)
,
b
≥
φ
(
m
)
a^{b}\equiv \left\{\begin{matrix} a^b\ ,b< \varphi(m)\\ a^{b\ mod\ \varphi(m)+\varphi(m)}\ ,b\geq \varphi(m) \end{matrix}\right.
ab≡{ab ,b<φ(m)ab mod φ(m)+φ(m) ,b≥φ(m)
代码
#include<cstdio>
long long a, m, b, phi, f, p;
int power(int a, int b) {
long long res = 1;
for (; b; b >>= 1) {
if (b & 1) res = res * a % p;
a = (long long)a * a % p;
}
return res;
}
int main() {
scanf("%d %d", &a, &m);
phi = p = m;
for (int i = 2; i * i <= m; i++) {
if (m % i) continue;
phi = phi / i * (i - 1);
while (m % i == 0) m /= i;
}
if (m > 1) phi = phi / m * (m - 1);
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9') {
b = b * 10 + c - 48;
if (b >= phi) b %= phi, f = 1;
c = getchar();
}
if (f) b += phi;
printf("%d", power(a, b));
}