采用二分法。
n!中因子2的个数比5多,所以因子5的个数等于末尾零的个数,只需要算出因子5的个数即可。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1000000000;
ll fac(int n,int x){
ll ans = 0;
while(n){
ans += n/x;
n /= x;
}
return ans;
}
int main(){
int t,q;
scanf("%d",&t);
for(int cas = 1;cas <= t;cas++){
scanf("%d",&q);
int l = 4,r = maxn;
while(l <= r){
int mid = (l+r)>>1;
if(fac(mid, 5)>=q)
r = mid - 1;
else
l = mid + 1;
}
if(fac(l, 5) != q)
printf("Case %d: impossible\n",cas);
else
printf("Case %d: %d\n",cas,l);
}
return 0;
}