P4139 上帝與集合的正確用法(尤拉降冪)
阿新 • • 發佈:2021-02-03
技術標籤:數論
P4139 上帝與集合的正確用法(尤拉降冪)
題意
求2的無窮層冪塔函式在模 p p p意義下的值。
思路
顯然最多遞迴至 l o g log log層,所以用尤拉降冪即可。
時間複雜度: O ( T l o g 2 p ) O(Tlog^2p) O(Tlog2p)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e3+5,M=2e4+5,inf=0x3f3f3f3f,mod=1e9+7;
#define mst(a,b) memset(a,b,sizeof a)
#define PII pair<int,int>
#define fi first
#define se second
#define pb push_back
#define mod(a,b) a<b?a:a%b+b
unordered_map<ll,ll>mp;
ll phi(ll n){
if(mp[n]) return mp[n];
ll s=n,nn=n;
for(ll i=2;i*i<=n;i++){
if(n%i==0){
s-=s/i;
while(n%i==0) n/=i;
}
}if(n>1) s-=s/n;return mp[nn]=s;
}
ll ksm(ll a,ll n,ll m){
ll s=1;
a=mod(a,m);
while(n){
if(n&1) s=mod(s*a,m);
a=mod(a*a,m);
n>>=1;
}return s;
}
ll solve(ll m){
if(m==1) return 1;
return ksm(2,solve(phi(m)),m);
}
int main(){
int T;scanf("%d",&T);while(T--){
int m;scanf("%d" ,&m);
printf("%lld\n",solve(m)%m);
}
return 0;
}