二分查找(Trailing Zeroes (III)(LightOJ1138))

二分查找:在有序数组中,寻找特定数的的算法。

步骤:

  1. 先在判断当前数组 中间值mid(mid=left+(right-left)/2))是否等于所找数字n,若是,返回mid。
  2. 若不是,n>fx(mid),说明n在数组靠近right的部分,left=mid+1;n<mid,n在数组靠近left部分,right=mid-1;继续进行1中的判断。
  3. 进入循环的条件是:while(left<=right),若找不到,返回找不到的相关信息。
    int binarysearch(int a,int b)
    {
    int left,right;
    while(left<=right)
    	{
    		int mid=low+(right-left)>>1;
    		if(n<fx(mid))
    			right=mid-1;
    		else if(n>fx(mid))
    			left=mid+1;
    		else return mid;
    	}
          return -1;
    }

    例题:Trailing Zeroes (III)(LightOJ1138)


    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 ≤ 108) 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


    题意:首先有T组测试数据,让你查找是否存在数字n,使n!末尾0的个数为Q。

        解题思路:末尾为0,则需要2*5,在一个数中,2的个数远远多于5,则找到一个包含5的个数与Q相等数,这个数可能有好几个,找到最小的输出。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MAXN=10000000000000;

ll f(ll n)//拆分min,看其包含多少个0 
{
    ll ans=0;
    while(n)    ans+=(n/=5);
    return ans;
}


int main()
{
    int t;ll Q;
    scanf("%d",&t);
    int kase=1;
    while(t--)
    {
        scanf("%lld",&Q);
        ll l=1,r=MAXN;
        ll ans=0;
        while(r>=l)//进行二分查找 
        {
            ll mid=(l+r)>>1;
            if(f(mid)==Q)
            {
                ans=mid;
                r=mid-1;//找到后继续缩小范围,确保数是最小的 
            }
            else if(f(mid)<Q)   l=mid+1;
            else                r=mid-1;
        }
        printf("Case %d: ",kase++);
        if(ans) printf("%lld\n",ans);
        else    printf("impossible\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Lyyforever1220/article/details/99341836
今日推荐