The Luckiest number
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(100+101+…+10(x−1)) ;
m=(8/9)∗(10x−1) ;
题目的要求就是 m=0(modL)
就是 (8/9)∗(10x−1)=0(modL) ;
8∗(10x−1)=0(mod9L) ;
10x−1=0(mod9L/gcd(L,8)) ;
10x=1(mod9L/gcd(L,8)) ;
10x==1(modp) ,求满足条件的最小的整数x
利用Euler定理,但是如果 if(gcd(10,p)!=1) ,即不互素,也就是不满足欧拉定理的条件了,所以返回0.
if(gcd(10,p)==1) 满足欧拉定理
由于 aφ(n)≡1modn ,所以答案是 φ(n) 的因子,然后枚举 φ(n) 的因子, 再检查模是否为1,找到最小的那个满足条件的就是最终答案
代码
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
typedef long long LL;
LL gcd(LL a,LL b)
{
return b == 0? a : gcd(b, a%b);
}
LL mul(LL a, LL b, LL mod)// a * b % c
{
LL res=0;
while(b)
{
if(b&1)
{
res = (res+a) % mod;
}
a = (a<<1) % mod;
b >>= 1;
}
return res;
}
LL quick(LL a, LL b, LL mod)
{
LL s=1,tmp=a;
while(b)
{
if(b & 1)
{
s = mul(s,tmp,mod);
}
tmp = mul(tmp,tmp,mod);
b >>= 1;
}
return s;
}
LL Euler(LL n)
{
LL m = (int)sqrt(n+0.5);
LL res = n;
for(LL i = 2; i <= m; ++i)
{
if(n%i == 0)
{
res = res / i * (i-1);
while(n%i == 0)
{
n /= i;
}
}
}
if(n > 1)
{
res = res / n * (n-1);
}
return res;
}
int main()
{
int cas = 0, d;
LL L,m;
while(cin>>L && L)
{
m = 9*L / gcd(L,8);
cout<<"Case "<<++cas<<": ";
d = gcd(10,m);
if(d == 1)
{
LL phi = Euler(m);
LL ans = phi;
LL p = sqrt((double)phi);
bool kk = 0;
for(int i = 1; i <= p; i++)
{
if(phi%i == 0 && quick(10, i, m) == 1)
{
ans=i;
kk=1;
break;
}
}
if(!kk)
{
for(int i=p; i >= 2; i--)
{
if(phi%i == 0 && quick(10, phi/i, m) == 1)
{
ans = phi/i;
kk = 1;
break;
}
}
}
cout<<ans<<endl;
}
else
{
cout<<"0"<<endl;
}
}
}