POJ 3358 Period of an Infinite Binary Expansion(欧拉定理)

推理部分这里给的比较清楚

代码如下:

#include <cstdio>
using namespace std;
const int maxn =1000+5;
typedef long long LL;
LL gcd(LL a,LL b)
{
    return b==0?a:gcd(b,a%b);
}
LL getph(LL x)
{
    LL ans=x;
    for(LL i=2;i*i<=x;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;
}
LL work(LL b,LL mod)
{
    LL r=1,a=2;
    while(b)
    {
        if(b&1) r=r*a%mod;
        a=(a*a)%mod;
        b>>=1;
    }
    return r;
}
int main()
{
    LL p,cas=0,q;
    while(~scanf("%I64d/%I64d",&p,&q))
    {
        printf("Case #%d: ",++cas);
        if(p==0){
            printf("1,1\n");
            continue;
        }
        q/=gcd(p,q);
        LL x=0;
        while(q%2==0) q/=2,x++;
        LL ans=getph(q);
        p=ans;
        LL res[50][2],k=0,pp=0;
        for(LL i=2;i*i<=p;i++)
            if(p%i==0){
                res[k][0]=i;
                res[k][1]=0;
                while(p%i==0) res[k][1]++,p/=i;
                k++;
            }
        if(p>1) res[k][0]=p,res[k++][1]=1;
        for(int i=0;i<k;i++)
            for(int j=1;j<=res[i][1];j++)
                if(work(ans/res[i][0],q)==1)
                    ans/=res[i][0];
        printf("%I64d,%I64d\n",x+1,ans);
    }
    return 0;
}


你可能感兴趣的:(POJ 3358 Period of an Infinite Binary Expansion(欧拉定理))