题解:P16634 [GKS 2017 #G] Huge Numbers

· · 题解

既然有这个 tag,显然地,使用欧拉降幂,则:

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}

直接计算即可。目前本题最优解。因为复杂度为 O(T(n+\sqrt p+\log \varphi(p)))=O(T(n+\sqrt p))。

不过也能线性筛做到 O(p+T(n+\log \varphi(p)))。

#include<bits/stdc++.h>
using namespace std;
inline int phi(int n){
    int ans=n;
    for(int i=2;i<=sqrt(n);i++){
        if(n%i)continue;
        while(!(n%i))n/=i;
        ans/=i;
        ans*=(i-1);
    }
    if(n>1)return ans/n*(n-1);//剩下的 n 是质数
    return ans;
}
inline int fac(int n,int pm){
    bool fl=0;
    int x=1;
    for(int i=1;i<=n;i++){
        x=1ll*x*i;
        if(x>=pm){
            x%=pm;
            fl=1;
        }
    }
    return x+fl*pm;
}
int qpow(int a,int b,int mod){
    if(b==0||a==1)return 1%mod;//mod 可以 ==1
    if(b==1)return a%mod;
    int h=qpow(a,b>>1,mod);
    return 1ll*h*h%mod*(b&1?a:1)%mod;
}
int lpow(int a,function<int(int,int)> gb,int mod,int N){
    int pm=phi(mod),b=gb(N,pm);
    if(b<pm)return qpow(a,b,mod);
    else return qpow(a,b%pm+pm,mod);
}
#define endl '\n'
#ifdef __linux__
#define getchar getchar_unlocked
#define putchar putchar_unlocked
#else
#define getchar _getchar_nolock
#define putchar _putchar_nolock
#endif
inline int read(){
    int x=0,f=1;char ch=getchar();
    while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
    while (ch>='0'&&ch<='9'){x=(x << 1) + (x << 3)+ch-48;ch=getchar();}
    return x*f;
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    int T=read();
    for(int t=1;t<=T;t++){
        int a,n,p;
        a=read(),n=read(),p=read();
        cout<<"Case #"<<t<<": "<<lpow(a,fac,p,n)<<endl;
    }

    return 0;
}