The Luckiest number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem 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
Source
2008 Asia Hefei Regional Contest Online by USTC
由题可得
8(10x−1)9=L×k
可以得到
10x−1=9L8×k
若令
m=9Lgcd(L,8)
则有
10x−1=m×gcd(L,8)8×k
及一定存在
k′=gcd(L,8)8×k
使得
10x−1=m∗k′
成立。
即
10x≡1 mod m
又因为
10φ(m)≡1 mod m
若存在
10a≡1 mod m
就一定有
10φ(m)/a≡1 mod m
我们便可以枚举
φ(m)
的因数,然后用快速幂判断即可。
注意,因为范围是longlong,故用大数乘法。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
#define MAXN
#define MAXM
#define INF 0x3f3f3f3f
#define LLF 0x3f3f3f3f3f3f3f3fll
typedef long long int LL;
LL gcd(LL a,LL b){return !b?a:gcd(b,a%b);}
bool isprime[200010];
int prime[200010],cnt;
void getprime(LL n)
{
memset(isprime,1,sizeof(isprime));
cnt=0;
for(int i=2;i<=n;++i)
{
if(isprime[i])
prime[++cnt]=i;
for(int j=1;j<=cnt&&i*prime[j]<=n;++j)
{
isprime[i*prime[j]]=0;
if(i%prime[j]==0)break;
}
}
}
LL euler(LL x)
{
LL rn=x;
for(int i=1;1ll*prime[i]*prime[i]<=x;++i)
if(x%prime[i]==0)
{
rn=rn/prime[i]*(prime[i]-1);
do{
x/=prime[i];
}while(x%prime[i]==0);
}
if(x>1)rn=rn/x*(x-1);
return rn;
}
LL Mul(LL a,LL b,LL mod)
{
LL rn=0;
while(b)
{
if(b&1)
rn=(rn+a)%mod;
a=(a<<1)%mod;
b>>=1;
}
return rn;
}
LL Ksm(LL a,LL p,LL mod)
{
LL rn=1;
while(p)
{
if(p&1)
rn=Mul(rn,a,mod);
a=Mul(a,a,mod);
p>>=1;
}
return rn;
}
LL L;
int main()
{
getprime(200000);
int Case=0;
while(~scanf("%I64d",&L)&&L)
{
int i,j;
LL m=9ll*L/gcd(L,8ll);
if(gcd(m,10)!=1)
{
printf("Case %d: 0\n",++Case);
continue;
}
LL val=euler(m);
LL ans=LLF;
LL end=sqrt(val+0.5);
for(i=1;i<=end;++i)
if(val%i==0)
{
if(Ksm(10ll,i,m)==1)ans=min(ans,(LL)i);
if(Ksm(10ll,val/i,m)==1)ans=min(ans,(LL)val/i);
}
printf("Case %d: %I64d\n",++Case,ans);
}
}
但如果这样暴力枚举因数的话要跑100+MS,时间复杂度恐怖啊。
。。于是有一种枚举质因数然后删去的神奇方法,我反正看不懂。
然后就可以31MS过了
int main()
{
getprime(200000);
int Case=0;
while(~scanf("%I64d",&L)&&L)
{
int i,j;
LL m=9ll*L/gcd(L,8ll);
if(gcd(m,10)!=1)
{
printf("Case %d: 0\n",++Case);
continue;
}
LL ans=euler(m);
for(i=1;i<=cnt&&prime[i]<=ans;++i)
while(ans%prime[i]==0&&Ksm(10ll,ans/prime[i],m)==1)
ans/=prime[i];
if(ans>1&&Ksm(10ll,ans/ans,m)==1)
ans/=ans;
printf("Case %d: %I64d\n",++Case,ans);
}
}