码迷,mamicode.com
首页 > 其他好文 > 详细

LightOJ Trailing Zeroes (III) 1138【二分搜索+阶乘分解】

时间:2015-08-20 22:39:23      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

1138 - Trailing Zeroes (III)
Time Limit: 2 second(s) Memory Limit: 32 MB

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

Output for Sample Input

3

1

2

5

Case 1: 5

Case 2: 10

Case 3: impossible

 


PROBLEM SETTER: JANE ALAM JAN


题意:给你一个数字,这个数字代表N!后面有几个0。给出这个数字,计算N的值。


解题思路:

任何质因数都可以写成素数相乘的形式。所以计算一个数的阶乘后面几个0,只需计算这个数包含多少5即可。(关于这点不清楚的点:点击打开链接)。

可以用二分法,找出这个点。想到用二分这道题也就没什么难度了。

AC代码;

<span style="font-size:18px;">#include <stdio.h>
#include <math.h>
#include <vector>
#include <queue>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;

LL solve(LL n)
{
    LL num=0;
    while(n){
        num+=n/5;
        n/=5;
    }
    return num;
}

LL er(LL n)
{
    LL x=1;
    LL y=1844674407370;
    LL mid;
    LL res=-1;
    while(y>=x){
        mid=(x+y)/2;
        LL ans=solve(mid);
        if(ans==n){
            res=mid;
            y=mid-1;
            //return mid;
        }
        else if(ans>n){
            y=mid-1;
        }
        else if(ans<n){
            x=mid+1;
        }
    }
    return res;
}
int main()
{

    int t;
    scanf("%d",&t);
    int xp=1;
    while(t--){
        LL n;
        scanf("%lld",&n);
        LL ans=er(n);
        if(ans==-1)  printf("Case %d: impossible\n",xp++);
        else printf("Case %d: %d\n",xp++,ans);
    }
    return 0;
}
</span>


版权声明:本文为博主原创文章,转载请注明出处。

LightOJ Trailing Zeroes (III) 1138【二分搜索+阶乘分解】

标签:

原文地址:http://blog.csdn.net/ydd97/article/details/47816067

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!