【poj3696】The Luckiest number

2015.04.15 16:48 Wed | 5次阅读 | 旧日oi | 固定链接 | 源码

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
题解
又是一道恶心的数学题
因为M全部由8组成,即M=(10^x -1)*8/9=k*N;
则    (10^x-1)*8/gcd(8,N)=9*k*N/gcd(8,N);
令p=8/gcd(8,N);        q=9*N/gcd(8,N);
 即    (10^x-1)*p=k*q;
由于p和q互质,则(10^x-1)%q==0;
根据同余定理可知,10^x ≡1(mod q)
根据欧拉定理可知当gcd(a,b)==1时,a^φ(b)≡1(mod b);
即可得出: 当gcd(10,q)!=1时,无解。
当gcd(10,q)==1时    10^φ(q)≡1(mod q),
通过枚举φ(q)的约数,最小的满足条件的约数就是ans。
最后一步涉及到原根的知识,就不证明了

我的程序

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define ll long long
#define maxn 50000
using namespace std;
ll n,cnt,ans;
ll prime[maxn],tot;
bool vis[maxn];
ll gcd(ll a,ll b)
{
    return b?gcd(b,a%b):a;
}
void get_prime()
{
    for(int i=2;i*i<=2000000000;i++)
    {
        if(!vis[i]) prime[++tot]=i;
        for(int j=1;j<=tot&&prime[j]*i*prime[j]*i<=2000000000;j++)
        {
            vis[i*prime[j]]=1;
            if(i%prime[j]==0) break;
        }
    }
}
ll get_phi(ll x)
{
    ll tmp=x;
    for(int i=1;i<=tot&&prime[i]<=x;i++)
    if(x%prime[i]==0) 
    {
        tmp=tmp*(prime[i]-1)/prime[i];
        while(x%prime[i]==0) x/=prime[i];
    }
    if(x>1) tmp=tmp/x*(x-1);
    return tmp;
}
ll qc(ll a,ll b,ll mod)
{
    ll ret=0;
    while(b)
    {
        if(b&1) ret=(ret+a)%mod;
        b>>=1;
        a=(a+a)%mod;
    }
    return ret;
}
ll qpow(ll a,ll k,ll mod)
{
    ll ret=1;
    while(k)
    {
        if(k&1) ret=qc(ret,a,mod);
        k>>=1;
        a=qc(a,a,mod);
    }
    return ret;
}
ll check(ll x,ll p)
{
    ll ans=0x3f3f3f3f3f3f3f3fll;
    for(ll i=1;i*i<=x;i++)
    {
        if(x%i==0) 
        {
            if(qpow(10,i,p)==1) ans=min(ans,i);
            if(qpow(10,x/i,p)==1) ans=min(ans,x/i);
        }
    }
    return ans;
}       
int main()
{
    get_prime();
    while(cin>>n&&n)
    {
        ll q=9*n/gcd(n,8);
        if(gcd(q,10)!=1) ans=0;
        else
        {
            ll num=get_phi(q);
            ans=check(num,q);
        }
        printf("Case %d: ",++cnt);
        cout<<ans<<endl;
    }
    return 0;
}```