LIGHT OJ 1138 - Trailing Zeroes (III)【N!后0的个数&&二分(好题)】

本文介绍了一种算法,用于寻找最小的自然数N,使得N!在十进制表示下恰好包含Q个尾随零。通过二分查找方法,在给定的Q值范围内高效地找到解或确定无解。

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!中5的个数依然可以用于统计>1的任何整数;


AC代码:

#include<cstdio>

typedef long long LL;
const LL INF=1e18;

LL Sum(LL N) {//N!后0的个数即统计N!能除以多少个5 直接统计1-N中5的倍数 
	LL ret=0; //考虑到1-N中有可能含有5的次方 所以缩小5倍之后继续统计 
	while(N) { //即依次统计能被5^1整除的个数 5^2整除的个数 5^3 .....
		N/=5; ret+=N;
	}
	return ret;
}
int main() {
	LL T,Kase=0; scanf("%lld",&T);
	while(T--) {
		LL Q; scanf("%lld",&Q);
	    LL R=INF,L=1,ans=INF;
	    while(L<=R) {
	    	LL mid=L+R>>1;
	        LL s=Sum(mid);
	        if(s==Q) {
	        	ans=mid;R=mid-1;
			}
			else if(s>Q) R=mid-1;
			else L=mid+1;
		}
		printf("Case %d: ",++Kase);
		if(ans>=INF)  puts("impossible");
		else printf("%lld\n",ans);
	} 
	return 0;
}

这是一道经典的位运算目,考察对二进制的理解和位运算的熟练程度。 目描述: 给定一个长度为 $n$ 的数组 $a$,初始时每个数的值都为 $0$。现在有 $m$ 个操作,每个操作为一次询问或修改。 对于询问,给出两个整数 $l,r$,求 $a_l \oplus a_{l+1} \oplus \cdots \oplus a_r$ 的值。 对于修改,给出一个整数 $x$,表示将 $a_x$ 的值加 $1$。 输入格式: 第一行两个整数 $n,m$。 接下来 $m$ 行,每行描述一次操作,格式如下: 1 l r:表示询问区间 $[l,r]$ 的异或和。 2 x:表示将 $a_x$ 的值加 $1$。 输出格式: 对于每个询问操作,输出一个整数表示答案,每个答案占一行。 数据范围: $1 \leq n,m \leq 10^5$,$0 \leq a_i \leq 2^{30}$,$1 \leq l \leq r \leq n$,$1 \leq x \leq n$ 输入样例: 5 5 2 1 2 3 1 2 4 2 2 1 1 5 输出样例: 0 2 解思路: 对于询问操作,可以利用异或的性质,即 $a \oplus b \oplus a = b$,将 $a_l \oplus a_{l+1} \oplus \cdots \oplus a_r$ 转化为 $(a_1 \oplus \cdots \oplus a_{l-1}) \oplus (a_1 \oplus \cdots \oplus a_r)$,因为两个前缀异或后的结果可以相互抵消,最后的结果即为 $a_1 \oplus \cdots \oplus a_{l-1} \oplus a_1 \oplus \cdots \oplus a_r = a_l \oplus \cdots \oplus a_r$。 对于修改操作,可以将 $a_x$ 对应的二进制数的每一位都分离出来,然后对应位置进行修改即可。由于只有加 $1$ 操作,所以只需将最后一位加 $1$ 即可,其余位不变。 参考代码:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值