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
题意:
题意:给你一个数L,让你求出最小的一个数能被L整除,这个数满足每一位都是8。
分析:
一个数字每一位都是8那么这样的数字可以写成
111...111×8=(10n−1+...+102+101+100)×8=10n−19×8 111...111 × 8 = ( 10 n − 1 + . . . + 10 2 + 10 1 + 10 0 ) × 8 = 10 n − 1 9 × 8
那么上面式子中的n就是位数长度
因为这个数字要能被L整除所以得到
L | 8×10n−19 L | 8 × 10 n − 1 9
↓ ↓
9L | 8×(10n−1) 9 L | 8 × ( 10 n − 1 )
设 d=gcd(8,L) d = g c d ( 8 , L )
可得到
9Ld | 8d×(10n−1) 9 L d | 8 d × ( 10 n − 1 )
很明显 9Ld 和 8d 9 L d 和 8 d 是互质的
所以有
9Ld | (10n−1) 9 L d | ( 10 n − 1 )
所以可以得到
(10n−1)=m×9Ld ( 10 n − 1 ) = m × 9 L d
所以根据同余式的定义可以写成
10n≡1 (mod 9Ld) 10 n ≡ 1 ( m o d 9 L d )
化简到这里我们想起了欧拉定理
如果10和 9Ld 9 L d 不互质那么必然是无解的
如果互质必然有 10ϕ(9Ld)≡1 (mod 9Ld) 10 ϕ ( 9 L d ) ≡ 1 ( m o d 9 L d )
但是题目要求是最小的指数,所以我们需要在 ϕ(9Ld) ϕ ( 9 L d ) 的因子中看是否有快速幂取模后等于1的,并且我们只需要判断它的因子就足够了
为什么呢
假设有个最小的数 f f 使的
必然有 10f≡(10f)k≡10fk≡ 10ϕ(9Ld)≡1k≡1(mod 9Ld) 10 f ≡ ( 10 f ) k ≡ 10 f k ≡ 10 ϕ ( 9 L d ) ≡ 1 k ≡ 1 ( m o d 9 L d )
所以f只能是 ϕ(9Ld) ϕ ( 9 L d ) 的因子
妈的做这个题的是哇了11法就是找不出错,最后乘法写了个快速乘法取模(快速幂改版)就过了???什么沙雕??
望大佬指点为啥,万分感激
code:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
ll L;
ll mul(ll a,ll b,ll mod){
ll ans = 0;
while(b){
if(b & 1)
ans = (ans + a) % mod;
a = (a + a) % mod;
b >>= 1;
}
return ans;
}
ll q_pow(ll a,ll b,ll mod){
ll ans = 1;
while(b){
if(b & 1)
ans = mul(ans,a,mod);//把这里改成快速乘就过了否则就wa??
a = mul(a,a,mod);
b >>= 1;
}
return ans;
}
ll Euler(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;
}
ll gcd(ll a,ll b){
return b ? gcd(b,a%b) : a;
}
int main(){
int cas = 0;
while(~scanf("%lld",&L)){
if(L == 0) break;
ll p = 9 * L / gcd(L,8);
ll d = gcd(10,p);
if(d != 1){
printf("Case %d: 0\n",++cas);
}
else{
ll phi = Euler(p);
ll ans = phi;
ll m = sqrt((double)phi);
bool flag = false;
for(int i = 1; i <= m; i++){//直接枚举前根号phi个phi的因子
if(phi % i == 0 && q_pow(10,i,p) == 1){
ans = i;
flag = true;
break;
}
}
if(!flag){//找不到的话再去枚举后面的
for(int i = m; i >= 2; i--){
if(phi % i == 0 && q_pow(10,phi/i,p) == 1){
ans = phi / i;
break;
}
}
}
printf("Case %d: %lld\n",++cas,ans);
}
}
return 0;
}