Problem
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
思路
题意是给你一个L,和数字88….88,问最短多少个8能被L整除?
经初步化简可得, 10x−1=9Lp8 10 x − 1 = 9 L p 8
我们令 d=gcd(9L,8)=gcd(L,8) d = g c d ( 9 L , 8 ) = g c d ( L , 8 )
令 m=9∗L/d m = 9 ∗ L / d ,则存在 p1 p 1 ,使 9∗L∗p/8=m∗p1 9 ∗ L ∗ p / 8 = m ∗ p 1
方程转化为 10x−1=m∗p1 10 x − 1 = m ∗ p 1
即求同余方程 10x≡1(mod m) 10 x ≡ 1 ( m o d m ) 的最小解
由欧拉定理: aφ(m)≡1 (mod m)wheregcd(a,m)=1 a φ ( m ) ≡ 1 ( m o d m ) w h e r e g c d ( a , m ) = 1
- 注意 φ(m) φ ( m ) 不一定是最小模m为1的指数,但可以证明这些指数都是 φ(m) φ ( m ) 的因子。因此可以将 φ(m) φ ( m ) 质因子分解,用每个素因子试除,每个素因子除到模 m m 不为1为止(此时要乘回去)。
如果gcd(10,m)!=1,则本题无解,因为m有因子2或5,显然中不会含有这些因子。 注意要用快速乘,不然爆long long 代码示例
#include<iostream>
#include<vector>
#include<assert.h>
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b)
{
if(b==0) return a;
return gcd(b,a%b);
}
ll get_phi(ll x)
{
ll res=x;
if(x==1) return 1;
for(int i=2;i*i<=x;++i){
if(x%i==0){
res-=res/i;
do{
x/=i;
}while(x%i==0);
}
}
if(x>1) res-=res/x;
return res;
}
ll mul(ll a,ll b,ll c)
{
ll res=0;
while(b)
{
if(b&1) res=(res+a)%c;
a=(a+a)%c;
b>>=1;
}
return res;
}
ll fast_exp(ll a,ll b,ll c)
{
ll res=1;
while(b)
{
if(b&1) res=mul(a,res,c);
a=mul(a,a,c);
b>>=1;
}
return res;
}
int main()
{
//cout<<get_phi(1e7)<<endl;
//cout<<fast_exp(2,5,5)<<endl;
ll l;
int tt=0;
while(cin>>l && l!=0)
{
tt++;
ll d=gcd(l,8);
ll m=9LL*l/d;//模数m可能大于2^31
assert(m!=1);
if(gcd(m,10)!=1) cout<<"Case "<<tt<<": "<<0<<endl;
else{
ll phi=get_phi(m);
ll tp=phi;
vector<ll> prime;
for(int i=2;i*i<=phi;++i){
if(phi%i==0){
prime.push_back(i);
do{
phi/=i;
}while(phi%i==0);
}
}
if(phi>1) prime.push_back(phi);
assert(prime.size());
//cout<<fast_exp(10,tp,m)<<endl;
for(int k=0;k<prime.size();++k){//log
int flag=1;
while(fast_exp(10,tp,m)==1)//loglog
{
if(tp%prime[k]){
flag=0;
break;
}
tp/=prime[k];
}
if(flag) tp*=prime[k];
}
assert(fast_exp(10,tp,m)==1);
cout<<"Case "<<tt<<": "<<tp<<endl;
}
}
return 0;
}