链接:
https://nanti.jisuanke.com/t/17414
题意:
求f(n) = n ^ f(n-1) % m
题解:
指数降幂公式
代码:
31 ll n, m; 32 33 ll getphi(ll n) { 34 ll ans = n; 35 for (ll i = 2; i*i <= n; i++) if (n%i == 0) { 36 ans -= ans / i; 37 while (n%i == 0) n /= i; 38 } 39 if (n > 1) ans -= ans / n; 40 return ans; 41 } 42 43 ll mod_pow(ll x, ll n, ll mod) { 44 int res = 1; 45 while (n) { 46 if (n & 1) res = res * x % mod; 47 x = x * x % mod; 48 n >>= 1; 49 } 50 return res; 51 } 52 53 ll f(ll n, ll m) { 54 if (m == 1) return 0; 55 if (n < 5) { 56 ll ans = 1; 57 rep(i, 1, n + 1) ans = mod_pow(i, ans, m); 58 return ans; 59 } 60 ll phi = getphi(m); 61 ll z = f(n - 1, phi); 62 ll ans = mod_pow(n, phi + z, m); 63 return ans; 64 } 65 66 int main() { 67 ios::sync_with_stdio(false), cin.tie(0); 68 cin >> n >> m; 69 cout << f(n, m) << endl; 70 return 0; 71 }