1. 程式人生 > >POJ 3696 The Luckiest Number【尤拉函式+快速冪+快速乘】

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

題解:P143。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define ll long long
using namespace std;
const int maxn = 1000010;
ll L, fact[maxn], p;
ll gcd(ll a, ll b){
    return b ? gcd(b, a%b) : a;
}
ll multi(ll a, ll b, ll c){
    ll res = a, ans = 0;
    while(b){
        if(b & 1) ans = (ans + res) % c;
        res = (res + res) % c;
        b >>= 1;
    }
    return ans;
}
ll quick_pow(ll a, ll b, ll c){
    ll ans = 1, res = a % c;
    while(b){
        if(b & 1) ans = multi(ans, res, c);
        res = multi(res, res, c);
        b >>= 1;
    }
    return ans;
}
ll 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;
}
int main()
{
    int cnt = 0;
    while(~scanf("%lld", &L) && L){
        int m = 0;
        ll d = gcd(L, 8);
        p = L * 9 / d;
        ll n = phi(p);
        for(ll i = 1; i*i <= n; i++){
            if(n % i == 0){
                fact[m++] = i;
                if(i != n/i) fact[m++] = n/i;
            }
        }
        sort(fact, fact+m);
        int flag = 0;
        for(int i = 0; i < m; i++){
            if(quick_pow(10, fact[i], p) == 1){
                flag = 1;
                printf("Case %d: %lld\n", ++cnt, fact[i]);
                break;
            }
        }
        if(!flag) printf("Case %d: 0\n", ++cnt);
    }
    return 0;
}