https://blog.csdn.net/lizhiwei2017/article/details/81543342
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
注意到凡是那种11111..... 22222..... 33333.....之类的序列都可用这个式子来表示:k*(10^x-1)/9
进而简化:8 * (10^x-1)/9=L * k (k是一个整数)
8*(10^x-1)=9L*k
d=gcd(9L,8)=gcd(8,L)
8*(10^x-1)/d=9L/d*k
令p=8/d q=9L/d p*(10^x-1)=q*k
因为p,q互质,所以q|(10^x-1),即10^x-1=0(mod q),也就是10^x=1(mod 9*L/d)
由欧拉定理可知,当q与10互质的时候,10^(φ(q))=1 (mod q),即必定存在一个解x。
而题目中要求的是最小的解,设为min,那么有a^min=1%q,因为要满足a^φ(q)=1%q,那么a^φ(q)肯定能变换成(a^min)^i。
所以接下来只要枚举φ(q)的因子,找出符合条件的最小者即可。
无解的时候就是q与10不互质的时候,因为若q与10有公因子d:
1.若d=2,q=2*k,那么10^x=2^x*5^x=1%2k
即2^x*5^x=1+2k*m,左边为偶数,右边为奇数,显然矛盾。
2.若d=5,q=5*k,那么10^x=2^x*5^x=1%5k
即2^x*5^x=1+5k*m,左边是5的倍数,右边不是5的倍数,显然矛盾。
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
#include<cmath>
#include<vector>
using namespace std;
typedef long long ll;
#define N 1000000
ll dp[N];
ll gcd(ll a, ll b) {
return b ? gcd(b,a%b): a;
}
//求欧拉函数
ll eular(ll n) {
ll m = n;
for (ll i = 2; i*i <= n; i++) {
if (n%i == 0) {
m -= m / i;
while (n%i == 0) {
n /= i;
}
}
}
if (n > 1)
m -= m / n;
return m;
}
//快速乘
ll multi(ll a, ll b, ll mod) {
a%=mod;
b%=mod;
ll res = 0;
while (b) {
if (b & 1) {
res = (res + a) % mod;
}
a = (a * 2) % mod;
b >>= 1;
}
return res;
}
//快速幂结合快速乘
ll quick_pow(ll a, ll b, ll mod) {
ll res = 1;
while (b) {
if (b & 1) {
res = multi(res, a, mod);
}
a = multi(a, a, mod);
b >>= 1;
}
return res;
}
int main() {
ll l,cnt=1;
while (~scanf("%lld", &l) && l) {
memset(dp, 0, sizeof(dp));
ll m = 9 * l / gcd(8, l);
//欧拉定理成立条件
if (gcd(10, m) != 1) {
cout << "Case " << cnt++ << ": " << 0<< endl;
continue;
}
ll ans = eular(m);
ll t = 0;
//记录欧拉函数的因子
for (ll i = 1; i*i <= ans; i++) {
if (ans%i == 0) {
dp[t++] = i;
if (ans != i * i)
dp[t++] = ans / i;
}
}
sort(dp, dp + t);//因子从小到大排
ll book;
//枚举欧拉函数的因子直到10^dp[i]=1(mod m);
for (ll i = 0; i < t; i++) {
if (quick_pow(10, dp[i], m) == 1) {
book = i;
break;
}
}
cout << "Case " << cnt++ << ": " << dp[book] << endl;
}
return 0;
}