Light oj 1138 - Trailing Zeroes (III) 二分法查找

题意:给你一个数Q,代表N!中   末尾连续0的个数。让你求出最小的N。

定理:求N!中  末尾连续0的个数

求法如下


LL sum(LL N)
{
    LL ans = 0;
    while(N)
    {
        ans += N / 5;
        N /= 5;
    }
    return ans;
}
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;  
const int maxn=1e9;  //开的大一点  小了会 wr
ll pre(ll x)
{
    ll cnt=0;
    while(x)
    {
        cnt+=x/5;
        x/=5;
    }
    return cnt;
}
int main()
{
    int t,k=1;
    scanf("%d",&t);
    while(t--)
    {
        ll p;
        scanf("%lld",&p);
        ll l=0,r=maxn;
        ll ans,cnt;
        while(r>=l)                //二分法
        {
            ans=(l+r)/2;
            if(pre(ans)>=p)
            {
                r=ans-1;
                cnt=ans;
            }
            else
                l=ans+1;
        }
        if(pre(cnt)!=p)
            printf("Case %d: impossible\n",k++);
        else
            printf("Case %d: %lld\n",k++,cnt);
    }

    return 0;
}

将代码中的 long long类型改为 int 型也能过  而且用的时间更少。 

猜你喜欢

转载自blog.csdn.net/qq_41837216/article/details/82114981