【题解】 P4139 上帝与集合的正确用法

\(Decription:\)

给出T组询问,每次给出一个p,求\(2^{2^{2^{2...}}} \mod {p}\)

\(Sample\) \(Input:\)

3
2
3
6

\(Sample\) \(Output:\)

0
1
4

一看这种题就是要降幂大法,每次把指数变小,递归求指数。

传入一个参数:当前的模数,每次用欧拉定理做一下。

复杂度:O(能过)

#include<bits/stdc++.h>
#define int long long 
using namespace std;
int T,tmp,cnt,x;
const int N=1e7;
int phi[N+2],p[N+2];
bool vis[N+5];
inline int power(int a,int b,int p){
    int ret=1;
    while(b>0){
        if(b&1) ret=(ret*a)%p;
        a=(a*a)%p;
        b>>=1;
    } 
    return ret;
}
inline int solve(int x){
    if(x==1) return 0;
    if(!(x&1))return power(2,solve(phi[x])+phi[x],x)%x;
    else return power(2,solve(phi[x]),x)%x;
}
signed main(){
    vis[1]=1;phi[1]=1;
    
    for(int i=2;i<=N;++i){
        if(!vis[i]) p[++cnt]=i,phi[i]=i-1;
        for(int j=1;j<=cnt && i*p[j]<=N;++j){
            vis[i*p[j]]=1;
            if(i%p[j]!=0) phi[i*p[j]]=phi[i]*phi[p[j]];
            else { phi[i*p[j]]=phi[i]*p[j];break;}
        }
    }
    scanf("%lld",&T);
    while(T--){
        scanf("%lld",&x);
        printf("%lld\n",solve(x));
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/JCNL666/p/10675944.html