题目链接: https://nanti.jisuanke.com/t/41299
题意:计算迭代次幂 的值。
扩展欧拉定理
先使用Eratosthenes筛或者线性筛求出1~N每个数的欧拉函数值,然后通过递归求解。
方法1:保守写法
# include <iostream>
const int N = 1e6 + 5;
typedef long long ll;
ll phi[N];
void init(int n) {
phi[1] = 1;
for (int i = 2; i <= n; i++) {
phi[i] = i;
}
for (int i = 2; i <= n; i++) {
if (phi[i] == i) {
for (int j = i; j <= n; j += i) {
phi[j] = phi[j] / i * (i - 1);
}
}
}
}
ll qpow(ll x, ll p, ll mod) {
ll ans = 1;
while (p) {
if (p & 1) {
ans = ans * x % mod;
}
x = x * x % mod;
p >>= 1;
}
return ans;
}
ll solve(ll a, ll b, ll p) {
if (b == 0) {
return 1;
}
if (p == 1) {
return 0; // AC
// return 1; // AC
}
ll P = solve(a, b - 1, phi[p]);
if (P < phi[p] && P) {
return qpow(a, P, p);
} else {
return qpow(a, P + phi[p], p);
}
}
int main() {
init(N - 5);
int T;
std::cin >> T;
while (T--) {
ll a;
ll b;
ll mod;
std::cin >> a >> b >> mod;
ll ans = solve(a, b, mod);
std::cout << (ans % mod) << "\n";
}
return 0;
}
方法2:在快速幂取模的时候把需要取模的数加上一个模数,递归时直接一次解出。
# include <iostream>
# include <cstdio>
const int N = 1e6 + 5;
typedef long long ll;
ll phi[N];
void init(int n) {
phi[1] = 1;
for (int i = 2; i <= n; i++) {
phi[i] = i;
}
for (int i = 2; i <= n; i++) {
if (phi[i] == i) {
for (int j = i; j <= n; j += i) {
phi[j] = phi[j] / i * (i - 1);
}
}
}
}
ll Mod(ll a, ll b) {
return a < b ? a : (a % b + b);
}
ll qpow(ll x, ll p, ll mod) {
ll ans = 1 % mod;
while (p) {
if (p & 1)
ans = Mod(ans * x, mod);
x = Mod(x * x, mod);
p >>= 1;
}
return ans;
}
ll solve(ll a, ll b, ll p) {
if (b == 0) {
return 1;
}
if (p == 1) {
return 1; // AC
// return 0; // WA
}
return qpow(a, solve(a, b - 1, phi[p]), p);
}
int main() {
init(N - 5);
int T;
scanf("%d", &T);
while (T--) {
ll a;
ll b;
ll mod;
scanf("%lld %lld %lld", &a, &b, &mod);
printf("%lld\n", solve(a, b, mod) % mod);
}
return 0;
}
那个注释部分,p==1时的返回值还没有弄懂