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
题解:P143。 设x个8连在一起是L的倍数,由题意可知,长度为x全8序列为:8*(10^x-1)/ 9 = L * p,即(10^x-1)=9 * L * p/8。令m=9 * L/gcd(L,8),则存在p',使9 * L * p/8=m * p',方程转换为(10^x-1)=m * p',即求同余方程10^x≡1(mod m)的最小解。
根据欧拉定理可知,10^Φ(m)≡ 1(mod m),而我们要求的是最小的解,所以答案肯定是Φ(m)的因子,所以只需要枚举Φ(m)的因子,然后检查模值是否为1即可。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define ll long long
using namespace std;
const int maxn = 1000010;
ll L, fact[maxn], p;
ll gcd(ll a, ll b){
return b ? gcd(b, a%b) : a;
}
ll multi(ll a, ll b, ll c){
ll res = a, ans = 0;
while(b){
if(b & 1) ans = (ans + res) % c;
res = (res + res) % c;
b >>= 1;
}
return ans;
}
ll quick_pow(ll a, ll b, ll c){
ll ans = 1, res = a % c;
while(b){
if(b & 1) ans = multi(ans, res, c);
res = multi(res, res, c);
b >>= 1;
}
return ans;
}
ll phi(ll n){
ll ans = n;
for(ll i = 2; i*i <= n; i++){
if(n % i == 0){
ans = ans / i * (i-1);
while(n % i == 0) n /= i;
}
}
if(n > 1) ans = ans / n * (n-1);
return ans;
}
int main()
{
int cnt = 0;
while(~scanf("%lld", &L) && L){
int m = 0;
ll d = gcd(L, 8);
p = L * 9 / d;
ll n = phi(p);
for(ll i = 1; i*i <= n; i++){
if(n % i == 0){
fact[m++] = i;
if(i != n/i) fact[m++] = n/i;
}
}
sort(fact, fact+m);
int flag = 0;
for(int i = 0; i < m; i++){
if(quick_pow(10, fact[i], p) == 1){
flag = 1;
printf("Case %d: %lld\n", ++cnt, fact[i]);
break;
}
}
if(!flag) printf("Case %d: 0\n", ++cnt);
}
return 0;
}