Trailing Zeroes (III) LightOJ - 1138
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!后面有几个0。给出这个数字,计算N的值。
解题思路:
任何质因数都可以写成素数相乘的形式。所以计算一个数的阶乘后面几个0,只需计算这个数包含多少5即可
然后用二分查找即可
code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll solve(ll n){
ll num = 0;
while(n){
num += n / 5;
n /= 5;
}
return num;
}
ll search(ll n){
ll l = 1,r = 1844674407370;
ll mid;
ll res = -1;
while(l <= r){
mid = (l + r) >> 1;
ll ans = solve(mid);
if(ans == n){
res = mid;
r = mid - 1;
}
else if(ans > n){
r = mid - 1;
}
else if(ans < n){
l = mid + 1;
}
}
return res;
}
int main(){
int t,cas = 0;
scanf("%d",&t);
while(t--){
ll n;
scanf("%lld",&n);
ll ans = search(n);
if(ans == -1)
printf("Case %d: impossible\n",++cas);
else
printf("Case %d: %lld\n",++cas,ans);
}
return 0;
}