【模板】欧拉定理(洛谷P5091)

https://ouuan.blog.luogu.org/solution-p5091

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int b[20000004],cnt=0,flag=0;
inline int phi(int p){
    int ans=p;
    int m=sqrt(p);
    for(int i=2;i<=m;i++){
        if(p%i==0){
            ans=ans/i*(i-1);
            while(p%i==0) p/=i;
        }
    }
    if(p>1) ans=ans/p*(p-1);
    return ans;
}
inline int mo(int h){
    long long ans=0;
    for(int i=1;i<=cnt;i++){
        ans=(long long)10*ans+b[i];
        if(ans>=h){
            flag=1;
            ans%=h;
        }
    }
    return ans;
}
inline int ksm(long long  a,int c,int p){
    long long ans=1;
    while(c){
        if(c&1) ans=ans*a%p;
        a=a*a%p;
        c>>=1;
    }
    return ans;
}
int main(){
    int a,p;
    scanf("%d",&a);
    scanf("%d",&p);
    char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    while(ch<='9'&&ch>='0'){
        b[++cnt]=ch-48;
        ch=getchar();
    }
    int h=phi(p);
    int c=mo(h);
    if(flag) c+=h;
    cout<<ksm(a,c,p);
}

 

posted @ 2019-01-02 08:35  WiFiMonster  阅读(258)  评论(0编辑  收藏  举报