Trailing Zeroes (III)

Trailing Zeroes (III)  LightOJ - 1138

        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


题意:找到一个最小的自然数,使得其阶乘的末尾连续的0的个数为Q个。


思路:找规律,不要试图求出阶乘。

规律:例:从1!到4!,末尾无0;5!到9!,末尾1个0;10!到14!,末尾2个0;

可发现5的倍数如5、10、15、20、25等等,都会提供1个0,25的倍数如25、50、75等等,都会加2个0,125的倍数如125、250等等会加3个0 .....往后以此类推。

方法:运用二分法,就是把mid当做答案验证,看看mid的阶乘后面的0,是不是Q个。

如何判断:例:mid=100

  1. mid/5,看mid中有几个5,有25个,意味着5、10、15、20.....提供了25个0

  2. mid/25,看mid中有几个25,有4个,意味着25、50、75、100会提供8个0,但第一步这4个数已经提供了4个0,故这一步提供了4个0

  3. mid/125,发现除不了,则结束了,一共提供了 29个0 故,答案为29

从上可发现,十分巧妙,只要求出有几个5,几个25,几个125,几个小于mid的5的次方,加起来就是答案。


#include<stdio.h>
int main()
{
	int t,z,ans,e;
	int mid,l,r,x;
	while(~scanf("%d",&t))
	{
		e=1;
		while(t--)
		{
			scanf("%d",&z);
			l=1,r=5e8,mid=(l+r)/2;
			while(l!=mid)
			{
				ans=0;
				x=mid;
				while(x!=0)
				{
					ans+=x/5;
					x/=5;
				}
				if( ans >= z)
				r=mid;
				else l=mid;
				mid = (l + r) / 2;
			}
			ans=0;
			x=mid+1;
			while(x!=0)
			{
				ans+=x/5;
				x/=5;
			}
			printf("Case %d: ",e++);
			if(ans==z)
			printf("%d\n",mid+1);
			else printf("impossible\n");
		}
	}
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值