Light oj Trailing Zeroes (III) (二分查找)

1138 - Trailing Zeroes (III)
PDF (English) Statistics Forum
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

 

题意:Q是N!的末尾的0的个数,求最小的N的值。
用到一个定理:除5求末尾0
法一:(递归)
long long f(long long n)
{
	if(n<5)
	 	return 0;
	else
		return n/5+f(n/5);
}


法二:(普通)
long long f(long long n)
{
	long long sum=0;
	while(n>0)
	{
		sum+=n/5;
		n=n/5;
	}
	return sum;
}


还有,l=mid,r=mid-1;具体还不知道是为什么~~
代码:
#include<cstdio>
long long f(long long n)
{
	if(n<5)
	 	return 0;
	else
		return n/5+f(n/5);
}
//long long f(long long n)
//{
//	long long sum=0;
//	while(n>0)
//	{
//		sum+=n/5;
//		n=n/5;
//	}
//	return sum;
//}
int main()
{
	int t,k=1;
	long long l,r,m,q,ans;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lld",&q);
		l=1;
		r=1000000000;
		ans=0;
		while(l<r)//二分查找N的值 
		{
			m=(l+r)/2;
			if(f(m)==q)
			{
				ans=m;
				r=m;
			}
			else if(f(m)<q)
			
				l=m+1;
			else
				r=m;			
		}
		if(ans)
			printf("Case %d: %lld\n",k++,ans);
		else
			printf("Case %d: impossible\n",k++);
	}
	return 0;
}


你可能感兴趣的:(Light oj Trailing Zeroes (III) (二分查找))