LightOJ-1138 Trailing Zeroes (III) (二分搜索)

http://acm.hust.edu.cn/vjudge/contest/view.action?cid=88668#problem/H

Trailing Zeroes (III)

Description

You task is to find minimal natural number N, so that N! contains exactly Q zeroes on the trail in decimal notation. As you know N! = 1*2*...*N. For example, 5! = 120, 120 contains one zero on the trail.

Input

Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case contains an integer Q (1 ≤ Q ≤ 108) in a line.

Output

For each case, print the case number and N. If no solution is found then print 'impossible'.

Sample Input

3

1

2

5

Sample Output

Case 1: 5

Case 2: 10

Case 3: impossible


题目描述:

  假设有一个数n,它的阶乘末尾有Q个零,现在给出Q,问n最小为多少?

解题思路:

  由于数字末尾的零等于min(因子2的个数,因子5的个数),又因为2<5,那么假设有一无限大的数n,n=2^x=5^y,可知x<<y。

所以我们可以直接根据因子5的个数,算阶乘末尾的零的个数。1<=Q<=10^8,所以可以用二分快速求解。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <queue>
#include <stack>
#include <vector>
#include <map>

using namespace std;

#define N 505
#define INF 0x3f3f3f3f
#define PI acos (-1.0)
#define EPS 1e-8
#define met(a, b) memset (a, b, sizeof (a))

long long findzeros (long long num);

int main ()
{
    long long t, n, flag=1;
    scanf ("%lld", &t);

    while (t--)
    {
        scanf ("%lld", &n);

        long long mid, l = 4, r = 500000000;
        while (l <= r)
        {
            mid = (l + r) / 2;

            long long num = findzeros (mid);

            if (num < n)
                l = mid + 1;
            if (num >= n)
                r = mid - 1;
        }
        if (findzeros (l) == n)
            printf ("Case %lld: %lld\n", flag++, l);
        else printf ("Case %lld: impossible\n", flag++);
    }
}

long long findzeros (long long num)
{
    long long ans = 0;

    while (num)
    {
        ans += num / 5;
        num /= 5;
    }
    return ans;
}


你可能感兴趣的:(LightOJ-1138 Trailing Zeroes (III) (二分搜索))