uvalive 10692 欧拉定理

a^x=a^(x%phi(c)+phi(c)) (mod c)

a^phi(c)=1 (mod c)


#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
//m^n%k
long long eular(long long n)
{
    long long ans=1,i;
    for(i=2; i*i<=n; i++)
    {
        if(n%i==0)
        {
            ans*=i-1;
            n/=i;
            while(n%i==0)
            {
                ans*=i;
                n/=i;
            }
        }
    }
    if(n>1)
    {
        ans*=n-1;
    }
    return ans;
}
long long quickpow(long long m,long long n,int k)
{
    long long b = 1;
    while (n > 0)
    {
        if (n & 1)
            b = (b*m)%k;
        n = n >> 1 ;
        m = (m*m)%k;
    }
    return b%k;
}
long long m,a[110],x;
int n;
char s[100];
long long e[110];
int main()
{
    int ca=1;
    while(scanf("%s",s))
    {
        if(s[0]=='#')break;
        m=0;
        int l=strlen(s);
        for(int i=0; i<l; i++)
        {
            m=m*10+(s[i]-'0');
        }
        scanf("%d",&n);
        for(int i=0; i<n; i++)scanf("%lld",&a[i]);
        e[0]=eular(m);
        for(int i=1;i<n;i++)e[i]=eular(e[i-1]);
        long long b;
        if(n!=1)
        b=a[n-1]%e[n-2];
        else b=a[n-1]%m;
        for(int i=n-2; i>=0; i--)
        {
            if(i)
            b=quickpow(a[i],b+e[i],e[i-1]);
            else b=quickpow(a[i],b+e[i],m);
        }
        cout<<"Case #"<<ca++<<": ";
        cout<<b<<endl;
    }
    return 0;
}


你可能感兴趣的:(Baoge)