欧拉降幂: $$ a^{b} \equiv\left{\begin{array}{ll}a^{b % \phi(p)} & g c d(a, p)=1 \a^{b} & g c d(a, p) \neq 1, b<\phi(p) \a^{b % \phi(p)+\phi(p)} & g c d(a, p)\neq 1, b \geq \phi(p)\end{array} \quad(\bmod p)\right. $$
ll qpow(ll a, ll b, ll mod){ //快速幂 ll res = 1; while (b) { if (b & 1) res = MOD(res * a, mod); a = MOD(a * a, mod); b >>= 1; } return res; }
ll getphi(ll x){ //求互质个数 ll ans = x; if (ma.count(x)) return ma[x]; for (int i = 2; i * i <= x; i++) { if (x % i == 0) { ans = ans / i * (i - 1); while (x % i == 0) x /= i; } } if (x > 1) ans = ans / x * (x - 1); //***** ma[x] = ans; return ans; } ll solve(int ceng, ll mod){ //每层的幂是w[i] if (ceng == r || mod == 1) return MOD(w[ceng], mod); return qpow(w[ceng], solve(ceng + 1, getphi(mod)), mod); }
intmain(){ int t; scanf("%d", &t); while (t--) { //scanf("%lld %lld %lld", &x, &r, &m); scanf("%lld %lld", &r, &m); if (!r) { cout << 1 % m << endl; continue; } //for (int i = 1; i <= r; i++) // 这个地方如果求幂塔函数(a^a^a^a^...)就这样写, 如果求a^b^c^d^...就自己输入w[i] //w[i] = x; for (int i = 1; i <= r; i++) scanf("%lld", &w[i]); printf("%lld\n", solve(1, m) % m); } return0; }