题目链接:
https://vjudge.net/problem/POJ-3696
题目:
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
题解:
x个8的正整数连在一起组成的正整数可以写作8(10^x-1)/9.题目让找最小的x,满足L|8(10^x-1)/9.设d=gcd(L,8)
L| 8(10^x-1)/9<==>9L|8(10^x-1)<==>9L/d | 8(10^x-1)/d
因为9L/d与8/d互质,所以9L/d 是(10^x-1)的因子。所以
引理:若正整数a,n互质,则满足 的最小正整数是φ(n)的约数。
所以我们求出φ(9L/d), 枚举它的所有约数,用快速幂去验证是否满足条件。
注意:9L比较大,可能两个long long 类型的数据乘起来可能爆long long,套个快速乘的板子。
代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std;
typedef long long ll;
const ll inf=1e18;
ll p;
ll euler(ll x){
ll ans=x;
for(int i=2;i*i<=x;i++){
if(x%i==0){
ans=ans/i*(i-1);
while(x%i==0) x/=i;
}
}
if(x>1) ans=ans/x*(x-1);
return ans;
}
ll gcd(ll a,ll b){
return b==0?a:gcd(b,a%b);
}
ll ksc(ll a,ll b){
a%=p,b%=p;
ll c=(long double)a*b/p;
ll ans=a*b-c*p;
if(ans<0) ans+=p;
else if(ans>=p) ans-=p;
return ans;
}
ll ksm(ll a,ll b){
a%=p;
ll ans=1;
while(b){
if(b&1) ans=ksc(ans,a)%p;
b>>=1;
a=ksc(a,a)%p;
}
return ans;
}
int main(){
int cnt=1;
while(scanf("%lld",&p)&&p){
p=p*9/gcd(p,8);
ll y=euler(p);
ll x=inf;
if(gcd(10,p)!=1){
printf("Case %d: 0\n",cnt++);
continue;
}
for(int i=1;i<=sqrt(y);i++){
if(y%i==0){
if(ksm(10,i)%p==1){
x=i;
break;
}
ll xx=y/i;
if(ksm(10,xx)%p==1){
x=min(x,xx);
}
}
}
printf("Case %d: %lld\n",cnt++,x);
}
return 0;
}