LightOJ 1138Trailing Zeroes (III)

来源:互联网 发布:淘宝集运4px递四方速递 编辑:程序博客网 时间:2024/06/06 00:14

http://acm.hust.edu.cn/vjudge/contest/view.action?cid=70017#overview

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 300#define INF 0x3f3f3f3f#define PI acos (-1.0)#define EPS 1e-8#define met(a, b) memset (a, b, sizeof (a))typedef long long LL;LL find_zero (LL n);int main (){    int t;    LL n, nCase = 1, l, r, mid;    scanf ("%d", &t);    while (t--)    {        scanf ("%lld", &n);        l = 0, r = 1000000000000;        while (l <= r)        {            mid = (l + r) / 2;            LL temp = find_zero (mid);            if (temp < n)                l = mid + 1;            else r = mid - 1;        }        if (find_zero (l) == n) printf ("Case %lld: %lld\n", nCase++, l);        else printf ("Case %lld: impossible\n", nCase++);    }    return 0;}LL find_zero (LL n){    LL ans = 0;    while (n)    {        ans += n / 5;        n /= 5;    }    return ans;}


0 0