【模板】歐拉定理

【題目描述】

給你三個正整數,\(a\)\(b\)\(m\),求:\(a^b \; mod \; m\)。(題目傳送門ios

【題解】

由擴展歐拉定理便可解出該題:
\[a^b \equiv \begin{cases}a^{b \, mod \varphi(m)} & gcd(a,m) =1 \\ a^b & c < \varphi(m) \,, gcd(a,m) \ne 1 \\ a^{(b \, mod \varphi(m)) + \varphi(m)} & c \ge \varphi(m) \,, gcd(a,m) \ne 1 \end{cases}\]ui

  • 計算\(\varphi(m)\)this

  • 邊輸入\(b\)邊取模spa

  • 分狀況計算code

\(Code:\)

#include<cstdio>
using namespace std;
#define ll long long
#define rg register
struct ios{
    template<typename TP>
    inline ios operator >> (TP &x)
    {
        TP f=1;x=0;rg char c=getchar();
        for(;c>'9' || c<'0';c=getchar()) if(c=='-') f=-1;
        for(;c>='0' && c<='9';c=getchar()) x=(x<<3)+(x<<1)+(c^'0');
        x*=f;
        return *this;
    }
    template<typename TP>
    inline ios operator << (TP x)
    {
        int top=0,s[66];
        if(x<0) x=-x,putchar('-');
        if(!x) putchar('0');
        while(x) s[++top]=x%10+'0',x/=10;
        while(top) putchar(s[top--]);
        return *this;
    }
    inline ios operator << (char s)
    {
        putchar(s);
        return *this;
    }
}io;
int a,m,p,b,n,f;
inline int read()
{
    int x=0;rg char c=getchar();
    for(;c>='0' && c<='9';c=getchar())
    {
        x=(x<<3)+(x<<1)+(c^'0');
        if(x>=p) f=1,x%=p;
    }
    if(x>=p) f=1,x%=p;
    return x;
}
inline int pow(int a,int b)
{
    int ans=1;
    for(;b;b>>=1)
    {
        if(b&1) ans=(ll)ans*a%m;
        a=(ll)a*a%m;
    }
    return ans%m;
}
int main()
{
//  freopen("testdata.in","r",stdin);
    io>>a>>m,p=n=m;
    for(rg int i=2;i*i<=n;++i)
    {
        if(n%i==0)
        {
            p=p/i*(i-1);
            while(n%i==0) n/=i;
        }
    }
//  io<<p<<' '<<n<<'\n';
    if(n>1) p=p/n*(n-1);
//  io<<p<<'\n';
    b=read();
    if(f) b+=p;
//  io<<b<<'\n';
    io<<pow(a,b);
    return 0;
}
相關文章
相關標籤/搜索