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
思路:
开始你可以发现所有的0都是由5与偶数乘得来,而偶数又是由2组成 。
2,5得10。在这之中2的个数不用去管,肯定够用。只需要去想5的个数与0个数的关系。
最后不难发现,一个数一共包含了几个5,就会有几个零;比如,
5以及5之前的数一共包含了1个5,所以末尾共有1个零;
20以及20之前的数一共包含了4个5(5自身为1个,10包含一个,15包含一个,20包含一个),所以末尾共有4个零;
25以及25之前的数一共包含了6个5(5,10包含一个,15包含一个,20包含一个,25包含另个(5*5等于25,所以25包含两个)),所以末尾共有6个零;
28以及28之前的数一共包含了6个5,所以末尾共有6个零;
……这样,我们只需要求出所要求的数n一共包含了几个5,然后在从0-500000000(因为Q最大是100000000,所以要查找的范围上限最大是500000000)中查找是否有一个数它所包含的5的个数等于n就行了,如果有等于n,那么输出查找到的这个数,如果没有,则输出不可能;
注意这里要用 二分查找会减少时间复杂度避免超时;
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
using namespace std;
typedef long long LL;
int num(int x)
{
int res=0;
while(x)
{
res+=x/5;
x=x/5;
}
return res;
}
int f(int n)
{
LL l,r,mid;
l=1,r=500000000;
while(l<r)
{
mid=(l+r)>>1;
if(num(mid)<n)
l=mid+1;
else
r=mid;
}
if(num(l)==n)
return l;
else
return 0;
}
int main()
{
int t,cas=1;
scanf("%d",&t);
while(t--)
{
int q;
scanf("%d",&q);
int ans=f(q);
if(ans)
printf("Case %d: %d\n",cas++,ans);
else
printf("Case %d: impossible\n",cas++);
}
return 0;
}