P5091 【模板】欧拉定理

思路

欧拉定理

当a与m互质时

\[a^ {\phi (m)} \equiv 1 \ \ (mod\ m) \]

扩展欧拉定理

当a与m不互质且\(b\ge \phi(m)\)时,

\[a^b \equiv a^{(b\%\phi(m))+\phi(m)} \ \ (mod\ m) \]

\(b<\phi(m)\)时,不一定正确

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define int long long
using namespace std;
int phi(int n){
    int ans=n,x=n;
    int up=sqrt(n+0.5);
    for(int i=2;i<=up;i++){
        if(x%i==0){
            ans=ans/i*(i-1);
            while(x%i==0)
                x/=i;
        }
    }
    if(x>1)
        ans=ans/x*(x-1);
    return ans;
}
int pow(int a,int b,int mod){
    int ans=1;
    while(b){
        if(b&1)
            ans=(ans*a)%mod;
        a=(a*a)%mod;
        b>>=1;
    }
    return ans;
}
char t[20001000];
signed main(){
    int a=0,b=0,c=0,f=true;
    scanf("%lld %lld",&a,&b);
    int mod=phi(b);
    scanf("%s",t+1);
    int len=strlen(t+1);
    for(int i=1;i<=len;i++){
        c=c*10+t[i]-'0';
        if(c>=mod){
            f=false;
            c%=mod;
        }
    }
    if(!f)
        c+=mod;
    printf("%lld\n",pow(a,c,b));
    return 0;
}
posted @ 2019-03-18 08:53  dreagonm  阅读(203)  评论(0编辑  收藏  举报