二分练习 --D - Trailing Zeroes (III)

时间:2022-07-24
本文章向大家介绍二分练习 --D - Trailing Zeroes (III),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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! = 12…*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 089Case 1: 5

Case 2: 10

Case 3: impossible

题意:就是输入一个数,表示一个数末尾零的个数,然后求最小满足这个条件的阶乘!非常好的一个题,考验思维数学等一系列知识,最后又要用到二分查找,真的很nice的一个题!!!我太i了!!!

思路: 阶乘的规律:从2开始(包括2)从右到左第一位必定是2的倍数 (不包含2),所以这些数乘5必定是0。1 ~ 4 没有0、5 ~ 9有 1个零、10 ~ 14 有2个零。15 ~ 19有3个零。所以看出规律,每 出现一次5就会增加一个0;

1.需要注意的是后缀0是由2,5相乘得来,因此只需看有多少个2,5即可 n = 5: 5!的质因子中 (2 * 2 * 2 * 3 * 5)包含一个5和三个2。因而后缀0的个数是1。 n = 11: 11!的质因子中(2^8 * 3^4 * 5^2 * 7)包含两个5和三个2。于是后缀0的个数就是2。

2质因子中2的个数总是大于等于5的个数。因此只要计数5的个数就可以了。

例如: 11中有两个5因此输出2.可用 n/5=2;

3.需要注意的是25中有25,20,15,10,5,但是25又可以分为5*5, 因此需要判断t=n/5后中t中的5的个数。

#include<bits/stdc++.h>
using namespace std;
const int maxw=5e8;
int search(int n)//找出n中5的个数 
{
	int ans=0;
	while(n)
	{
		ans+=(n/5);//ans为商的累加,即5的个数
		n/=5;
	}
	return ans;
}
int main()
{
	int t,n;
	cin>>t;
	while(t--){
		cin>>n;
		int head=4,tail=maxw,mid,num;
		while(head<=tail){
			mid=(head+tail)/2;
			num=search(mid);
			if(num<n)
			head=mid+1;
			else
			tail=mid-1;
		}
		num=search(head);
		if(num==n)
			cout<<"Case "<<i<<": "<<head<<endl;
		else
			cout<<"Case "<<i<<": impossible"<<endl;
	}
	 return 0;
}