1. 程式人生 > >Trailing Zeroes (III)【N!後0的個數&&二分(好題)】

Trailing Zeroes (III)【N!後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!中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;
}