正文
增加 28 行删除 9 行
123456789101120 行未改动323334353637383940414243444546474849505152我们需要计算 $A^{N!} \bmod P$,但是阶乘作为指数太大了,考虑优化。根据 [欧拉定理](https://oi-wiki.org/math/number-theory/euler-totient/#%E6%AC%A7%E6%8B%89%E5%AE%9A%E7%90%86) 可得,$A^{N!} \bmod P = A^{(N! \bmod \phi(P) + \phi(p))} \bmod P$。```cpp#include <iostream>using namespace std;#define int long long20 行未改动return res;}signed main() {ios::sync_with_stdio(false); cin.tie(0);int T; cin >> T;for (int cas = 1; cas <= T; cas++) {int A, N, P;cin >> A >> N >> P;int phip = phi(P);int e = 1;for (int i = 2; i <= N; i++) {e = e * i % phip;}int ans = qpow(A, e + phip, P);cout << "Case #" << cas << ": " << ans << "\n";}return 0;}12345678910111213141516171820 行未改动394041424344454647484950515253545556575859606162636465666768697071upd 6.1: 感谢 @rdsabw1o 大佬指出“欧拉降幂要分讨”的 bug 并 hack 掉错解。我们需要计算 $A^{N!} \bmod P$,但是阶乘作为指数太大了,考虑优化。根据 [欧拉定理](https://oi-wiki.org/math/number-theory/euler-totient/#%E6%AC%A7%E6%8B%89%E5%AE%9A%E7%90%86) 可得,$A^{N!} \bmod P = A^{(N! \bmod \phi(P) + \phi(P))} \bmod P$。这个是错的。欧拉降幂一定要分类讨论啊。$$A^{N!}\bmod P=\begin{cases}A^{N!}\bmod P,&N!<\varphi(P)\\A^{N!\bmod \varphi(P)+\varphi(P)}\bmod P,&N!\ge \varphi(P)\end{cases}$$```cpp#include <iostream>using namespace std;#define int long long20 行未改动return res;}signed main() {int T;cin >> T;for (int cas = 1; cas <= T; cas++) {int A, N, P;cin >> A >> N >> P;if (P == 1) {cout << "Case #" << cas << ": 0\n";continue;}int phip = phi(P);int fact = 1;bool over = false; // 标记 N! >= phipfor (int i = 2; i <= N; i++) {fact *= i;if (fact >= phip) {over = true;fact %= phip;}}int ans;if (over) {ans = qpow(A, fact + phip, P);} else {ans = qpow(A, fact, P);}cout << "Case #" << cas << ": " << ans << "\n";}return 0;}