LightOJ

题意:求阶乘尾部有Q(1 ≤ Q ≤ 108)个0的最小N

分析:如果给出N,然后求N!尾部0的个数的话,直接对N除5分解即可(因为尾部0肯定是由5*2构成,那么而在阶乘种,2的因子个数要比5少,所以求阶乘中因子5的个数就是尾部0的个数)。本题是给出尾部0的个数,逆推N。如果从小到大枚举的话,肯定会超时。

一般这种问题,可以用二分的方法搜答案。得到答案之后再向下逼近。

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long LL;
int cnt(int N)
{
    int cnt=0;
    while(N){
        cnt+=N/5;
        N/=5;
    }
    return cnt;
}

int main()
{
    #ifndef ONLINE_JUDGE
            freopen("in.txt","r",stdin);
            freopen("out.txt","w",stdout);
    #endif
    int T,N,cas=1;
    scanf("%d",&T);
    while(T--){
        scanf("%d",&N);
        int L=1,R=1000000000,ans=-1;
        while(L<=R){
            int m = L+(R-L)/2;
            int re = cnt(m);
            if(re==N){
                while(m%5!=0) m--;      //向下逼近
                ans = m;
                break;
            }
            else if(re<N)  L = m+1;
            else R = m-1;
        }
        printf("Case %d: ",cas++);
        if(ans>0) printf("%d
",ans);
        else printf("impossible
");
    }   
    return 0;
}
为了更好的明天
原文地址:https://www.cnblogs.com/xiuwenli/p/9453928.html