【题解】poj3696 The Luckiest number 欧拉函数+快速幂

题目链接

Description

Chinese people think of ‘8’ as the lucky digit. Bob also likes digit ‘8’. Moreover, Bob has his own lucky number L. Now he wants to construct his luckiest number which is the minimum among all positive integers that are a multiple of L and consist of only digit ‘8’.

Input

The input consists of multiple test cases. Each test case contains exactly one line containing L(1 ≤ L ≤ 2,000,000,000).

The last test case is followed by a line containing a zero.

Output

For each test case, print a line containing the test case number( beginning with 1) followed by a integer which is the length of Bob’s luckiest number. If Bob can’t construct his luckiest number, print a zero.

Sample Input

8
11
16
0

Sample Output

Case 1: 1
Case 2: 2
Case 3: 0


打不来公式的孩子……证明部分可见李煜东《算法竞赛进阶指南》和大佬博客,我代码对照着调了错,发现乘法那里还只能像大佬那样写成函数……

#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=5e4+10;
ll l;
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
bool iscomp[N];
int prime[N],p;
vector<int>y;
void primetable()
{
    for(int i=2;i<=50000;i++)
    {
        if(!iscomp[i])prime[p++]=i;
        for(int j=0;j<p&&i*prime[j]<=50000;j++)
        {
            iscomp[prime[j]*i]=1;
            if(i%prime[j]==0)break;
        }
    }
}
ll phi(ll n)
{
    ll ans=n;
    for(int i=0;prime[i]<=sqrt(n);i++)
    if(n%prime[i]==0)
    {
        ans=ans/prime[i]*(prime[i]-1);
        while(n%prime[i]==0)n/=prime[i];
    }
    if(n>1)ans=ans/n*(n-1);
    return ans;
}
bool flag;
int ca;
ll mul(ll a,ll b,ll mod)
{
    ll ans=0;
    while(b)
    {
        if(b&1)ans=(ans+a)%mod;
        a=(a+a)%mod;
        b>>=1;
    }
    return ans;
}
ll qpow(ll num,ll mi,ll mod)
{
    ll ans=1;
    while(mi)
    {
        if(mi&1)ans=mul(ans,num,mod);
        num=mul(num,num,mod);
        mi>>=1;
    }
    return ans;
}
void div(ll n)
{
    y.clear();
    for(int i=0;prime[i]<=sqrt(n);i++)
    while(n%prime[i]==0)
    {
        y.push_back(prime[i]);
        n/=prime[i];
    }
    if(n>1)y.push_back(n);
}
int main()
{
    //freopen("in.txt","r",stdin);
    primetable();
    while(scanf("%lld",&l)&&l)
    {
        flag=true;
        l=l*9/gcd(l,8);
        if(gcd(l,10)!=1){printf("Case %d: 0\n",++ca);continue;}
        ll ph=phi(l),len=ph;
        while(flag)
        {
            flag=false;
            div(ph);//得到所有约数
            for(int i=0;i<y.size();i++)
            {
                if(qpow(10,ph/y[i],l)==1)
                {
                    flag=true;
                    len=min(len,ph/y[i]);
                }
            } 
            ph=len;
        }
        printf("Case %d: %lld\n",++ca,len);
    }
    return 0;
}

总结

依旧是一个公式推导

猜你喜欢

转载自blog.csdn.net/qq_41958841/article/details/82502330