1. 程式人生 > 其它 >POJ 3696 尤拉函式的應用

POJ 3696 尤拉函式的應用

The Luckiest number
Time Limit:1000MS Memory Limit:65536K
Total Submissions:10897 Accepted:2769

Description

Chinese people think of '8' as the lucky digit. Bob also likes digit '8'. Moreover, Bob has his own lucky numberL. Now he wants to construct his luckiest number which is the minimum among all positive integers that are a multiple ofL

and consist of only digit '8'.

Input

The input consists of multiple test cases. Each test case contains exactly one line containingL(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

2008 Asia Hefei Regional Contest Online by USTC
//關鍵在於尤拉函式a^φ(n)≡1 (mod n)此時不能保證 φ(n)是最小的^x≡1 (mod n)
/*證明;x0為a^x≡1 (mod n)的最小值且x0為x的因子;

若不然 
設φ(n)=ax0+r;r不為0;
a^ax0*a^r≡1(mod n)
==>a^r≡1(mod n) ,與假設x0為最小矛盾,因為r<x0;

*/

#include<iostream>
#include<vector>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b){
	return !b?a:gcd(b,a%b);
}
ll quimul(ll a,ll b,ll mod)
{
	ll ans=0;
	while(b)
	{
		if(b&1)ans=(ans+a)%mod;
		b>>=1;
		a=(a+a)%mod;
	}
	return ans;
}
ll quipow(ll a, ll n,ll mod)
{
	ll ans=1%mod;
	while(n)
	{
		if(n&1)ans=quimul(ans,a,mod);
		n>>=1;
		a=quimul(a,a,mod);
	}
	return ans;
}
ll euler( ll n)
{
	ll ans=n;
	for(int i=2;i*i<=n;i++)
	{
		if(n%i==0)
		{
			ans=1ll*ans/i*(i-1);
			while(n%i==0)n/=i;
		}
	}
	if(n>1)ans=1ll*ans/n*(n-1);
	return ans;
}
int main()
{
	ll L,tot=1;
	while(~scanf("%lld",&L)&&L)
	{
		ll ans=0;
		ll d=gcd(L,8LL);
		ll mod=1ll*9*L/d,n;
		vector<ll>f;
		ll gd=gcd(10LL,mod);
		
		if(gd!=1){
			printf("Case %lld: %lld\n",tot++,0ll);
			continue;
		}
		n=euler(mod);
		for(ll i=1;i*i<=n;i++)
		{
			if(n%i==0)
			{
				f.push_back(i);
				if(1ll*i*i!=n)f.push_back(n/i);
			}
		}
		sort(f.begin(),f.end());
		for(ll i=0;i<f.size();i++)
		{
			if(quipow(10,f[i],mod)==1)
			{
				ans=f[i];
				break;
			}
		}
		printf("Case %lld: %lld\n",tot++,ans);
	}
	return 0;
}