LightOJ - 1138 (二分+阶乘分解)

题意:求阶乘尾部有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\n",ans);
        else printf("impossible\n");
    }   
    return 0;
}

 

转载于:https://www.cnblogs.com/xiuwenli/p/9453928.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值