LightOJ – 1138 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! = 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

求\(n!\) 末尾有多少个零。可以发现在\(n!\)所有的质因子中,只有2*5才会出现0,又因为2的个数比5的个数更多,所以此时转化为n!中有多少个5。

根据《挑战程序设计竞赛》P293,\(n!=ap^e\) p是素数且无法被a整除。则\(e={n/p+n/p^2+n/p^3+…}\)因为\(n/d\)和不超过n且能被d整除的数的个数相等。

#include<iostream>
#include<stdio.h>
using namespace std;
typedef long long ll;
ll t,q;
ll fundf(ll n)
{
	ll res=0;
	while(n)
	{
		res+=n/5;
		n/=5;
	}
	return res;
}
int main()
{
	scanf("%lld",&t);
	for(int i=1;i<=t;i++)
	{
		scanf("%lld",&q);
		printf("Case %d: ",i);
		ll l=0,r=1e14;
		while(r-l>1)
		{
			ll mid=(l+r)>>1;
			if(fundf(mid)>=q) r=mid;
			else l=mid;
		}
		if(fundf(r)==q) printf("%lld",r);
		else if(fundf(l)==q) printf("%lld",l);
		else printf("impossible");
	}
}

 

发表评论