E - Trailing Zeroes (III)
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 ≤ 10^8) 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!尾部有几个零可以用以下代码解决,解决这个问题,这道题就简单多了
int zero(int n)//此函数求n!末尾有几个0;
{
int ans=0;
while(n)
{
ans+=n/5;
n/=5;
}
return ans;
}
上面的代码原理参考博客https://blog.csdn.net/ee8736199/article/details/48105017
AC代码
#include<iostream>
#include<cstdio>
using namespace std;
int zero(int n)//此函数求n!末尾有几个0;
{
int ans=0;
while(n)
{
ans+=n/5;
n/=5;
}
return ans;
}
int main()
{
int t,q,k=1;
cin>>t;
while(t--)
{
cin>>q;
int left,right,ans=0,mid;//ans储存要求的结果
//使用二分法
left=1,right=(int)1e9;//因为题目中n!最多Q=1e8个0;所以将n最大设置为1e9足够了;
while(left<=right)
{
mid=(left+right)/2;
if(zero(mid)==q)
{
ans=mid;//满足用ans记下,因为要求最小的n,所以下面将right=mid-1,继续循环向小值逼近;
right=mid-1;
}
else if(zero(mid)>q)
right=mid-1;
else
left=mid+1;
}
if(ans)
printf("Case %d: %d\n",k++,ans);
else
printf("Case %d: impossible\n",k++);
}
return 0;
}
写的第一个博客,代码有水的地方欢迎大佬留言指点