您的位置:首页 > 大数据 > 人工智能

LightOJ 1138 Trailing Zeroes (二分+阶乘分解+思维)

2016-08-23 20:49 351 查看
1138 - Trailing Zeroes (III)



PDF (English)StatisticsForum
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即可。

因为只有2*5 才会出现 0   又因为2的数量肯定比5的多  所以计算阶乘中5的数量就可以得到该阶乘后有几个0。

50/5=10  10/5=2  所以50!后有10+2=12个0。

可以用二分法,找出这个点。想到用二分这道题也就没什么难度了。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
LL judge(LL mid)
{
LL sum=0;
while(mid)
{
sum+=mid/5;
mid/=5;
}
return sum;
}
int main()
{
int t;
scanf("%d",&t);
int flag=1;
while(t--)
{
LL n;
scanf("%lld",&n);
LL l=1,r=1000000000;
LL mid;
while(l<=r)
{
mid=(l+r)>>1;
if(judge(mid)>=n)
r=mid-1;
else
l=mid+1;
}
if(n==judge(l))
printf("Case %d: %lld\n",flag++,l);
else printf("Case %d: impossible\n",flag++);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: