POJ3696 The Luckiest number

题意

Language:
The Luckiest number
Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 7083Accepted: 1886

Description

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

Source

分析

[ecause L | frac{8(10^x-1)}{9} \ herefore 9L | 8(10^x-1) \ herefore frac{9L}{gcd(L,8)} | 10^x-1 \ herefore 10^x equiv 1 (mod frac{9L}{gcd(L,8)}) \ ecause a^x equiv 1 (mod n) ightarrow gcd(a,n)=1,x|varphi(n) \ herefore x|varphi(frac{9L}{gcd(L,8)}) ]

所以枚举即可。时间复杂度(O(sqrt{L} log L))

代码

#include<iostream>
#include<cmath>
#define rg register
#define il inline
#define co const
template<class T>il T read(){
	rg T data=0,w=1;
	rg char ch=getchar();
	while(!isdigit(ch)){
		if(ch=='-') w=-1;
		ch=getchar();
	}
	while(isdigit(ch))
		data=data*10+ch-'0',ch=getchar();
	return data*w;
}
template<class T>il T read(rg T&x){
	return x=read<T>();
}
typedef long long ll;

ll L,d,k,p,s,i,num=0;
ll gcd(ll x,ll y){
	return y?gcd(y,x%y):x;
}
ll ksc(ll a,ll b,ll c){
	ll ans=0;
	while(b){
		if(b&1) ans=(ans+a)%c;
		a=a*2%c;
		b>>=1;
	}
	return ans;
}
ll ksm(ll a,ll b,ll c){
	ll ans=1%c;
	a%=c;
	while(b){
		if(b&1) ans=ksc(ans,a,c);
		a=ksc(a,a,c);
		b>>=1;
	}
	return ans;
}
ll phi(ll n){
	ll ans=n;
	for(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 number(){
	d=gcd(L,8);
	k=9*L/d;
	if(gcd(k,10)!=1) return 0;
	p=phi(k);
	s=sqrt((double)p);
	for(i=1;i<=s;++i)
		if(p%i==0&&ksm(10,i,k)==1)
			return i;
	for(i=s-1;i;--i)
		if(p%i==0&&ksm(10,p/i,k)==1)
			return p/i;
	return 0;
}
int main(){
//	freopen(".in","r",stdin);
//	freopen(".out","w",stdout);
	while(read(L)) printf("Case %lld: %lld
",++num,number());
	return 0;
}
原文地址:https://www.cnblogs.com/autoint/p/10440135.html