题目
描述
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 starts with an integer T (≤ 10000), denoting the number of test cases.
Each case contains an integer Q (1 ≤ Q ≤ 108) in a line.
输出
For each case, print the case number and N. If no solution is found then print ‘impossible’.
样例输入
3
1
2
5
样例输出
Case 1: 5
Case 2: 10
Case 3: impossible
思路
经过一番思考,我们可以发现末尾的0是由 N! 中的5生成的,所以题目就便成了 N! 中所含5个因子的个数
然后就是
二分!二分!二分!
搜索!搜索!搜索!
因为我们在已知N的情况下很容易求出对应的Q,然后就是
二分!二分!二分!
搜索!搜索!搜索!
(重要的事情说三遍)
代码
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <stack>
using namespace std;
long long n;
long long get_5(long long n)
{
long long ans=0;
long long five=5;
while(n>=five)
{
ans+=n/five;
five*=5;
}
return ans;
}
long long solve(long long l,long long r)
{
long long mid=(l+r)/2;
long long tmp=get_5(mid);
if(l==r)
{
if(get_5(mid)==n)
return mid;
else
return -1;
}
if(tmp<n)
{
return solve(mid+1,r);
}
else if(tmp>n)
{
return solve(l,mid);
}
else
return mid;
}
int main()
{
int t;
scanf("%d",&t);
for(int cases=1;cases<=t;cases++)
{
scanf("%lld",&n);
long long ans=solve(0,1000000000000);
if(ans==-1)
printf("Case %d: impossible\n",cases);
else
{
while(get_5(ans-1)==n)
ans--;
printf("Case %d: %lld\n",cases,ans);
}
}
return 0;
}
代码来自这儿
不是俺写的,因为我不是这样写的
俺的写法:
#include <iostream>
using namespace std;
int Num[15];
int GetN(int N)
{
int Step=1;
int Count;
int Left;
int i;
if(N==0)
return 0;
for(i=2;i<=15;i++)
if(N>=Num[i])
Step*=5;
else
break;
Count=N/Num[i-1];
if(Count==5)
return -1;
Left=GetN(N%Num[i-1]);
if(Left==-1)
return -1;
else
return Count*Step+Left;
}
void Init()
{
Num[1]=1;
for(int i=2;i<=15;i++)
Num[i]=Num[i-1]*5+1;
}
int main()
{
int T;
int N;
int Result;
cin>>T;
Init();
for(int Case=1;Case<=T;Case++)
{
cin>>N;
Result=GetN(N)*5;
if(Result!=-5)
cout<<"Case "<<Case<<": "<<Result<<endl;
else
cout<<"Case "<<Case<<": impossible"<<endl;
}
return 0;
}
写的难看效率还低…
不爽!不爽!不爽!