Poj-3696 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


分析: WA到懷疑人生,最後找了網上的代碼發現是取模時溢出了...

88888....可以表示爲(10^k-1)/9*8,現在我們想讓(10^k-1)/9*8 = L*m,也就是8*(10^k-1) = 9*L*m,去掉8和L的公約數,整個式子可以化簡爲p*(10^k-1) = m*q,其中p q互質,那麼我們就是要找到最小的k使得
(10^k-1) % q = 0,也就是10^k   1 (% q),如果q和10不互質則無解,否則我們可以先用歐拉函數求出一個解,然後枚舉這個解的所有因數來得到最小的解.

#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <math.h>
using namespace std;
typedef long long  ll;
int Time;
ll l;
ll muti(ll a,ll b,ll MOD)
{
    ll ans = 0;
    while(b)
    {
        if(b & 1) ans = (ans + a) % MOD;
        a = (a<<1) % MOD;
        b>>=1;
    }
    return ans;
}
ll ksm(ll x,ll y,ll MOD)
{
    ll ans = 1;
    while(y)
    {
        if(y & 1) ans = muti(ans,x,MOD);
        x = muti(x,x,MOD);
        y >>= 1;
    }
    return ans;
}
ll euler_phi(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 log_mod(ll a,ll b)
{
    ll temp = euler_phi(b),now = temp;
 //   cout<<temp<<endl;
    if(now == 1) return now;
    for(ll i = 1;i*i <= temp;i++)
     if(temp % i == 0)
     {
        if(ksm(a,i,b) == 1)
        {
            now = min(now,i);
            break;
        }
        if(ksm(a,temp/i,b) == 1) now = min(now,temp/i);
     }
    return now;
}
int main()
{
	while(cin>>l && l)
	{
		ll p = 9*l/__gcd(l,8ll);
        if(__gcd(p,10ll) != 1ll)  printf("Case %d: 0\n",++Time);
		else printf("Case %d: %I64d\n",++Time,log_mod(10,p));
	}
}
/*/
999999999
2000000000
/*/



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章