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 |
Output for Sample Input |
3 1 2 5 |
Case 1: 5 Case 2: 10 Case 3: impossible |
题意:找到一个最小自然数N,满足N的阶乘后面Q个0.
分析:二分扫一下大区间, 然后由算数基本定理可知N!可以转换为素因子相乘的形式N! = 2^a+3^b + ......
10只能由2和5相乘得到,而2的个数比5多,所以只用求5的个数即可。
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
long long n;
long long get_five(long long m)///函数解释链接http://blog.csdn.net/ydd97/article/details/47083319
{
long long five = 5;
long long ans = 0;
while(m >= five)
{
ans += m / five;
five *= 5;
}
return ans;
}
long long solve(long long l, long long r)
{
long long mid = (l + r) / 2;
long long ans = get_five(mid);
if( l == r)
{
if(ans == n)
return mid;
else
return -1;
}
if(ans > n)
{
solve(l, mid );
}
else if(ans < n)
{
solve(mid + 1, r);
}
else
return mid;
}
int main()
{
int T, cas;
scanf("%d", &T);
cas = 0;
while(T--)
{
cas++;
scanf("%lld", &n);
long long ans = solve(0, 10000000000000);
printf("Case %d: ", cas);
if(ans == -1)
printf("impossible
");
else
{
while(get_five(ans-1) == n)///找最小值。
ans--;
printf("%lld
", ans);
}
}
return 0;
}