4! = 24
5! = 120 (满足末尾有1个0的最小N是5)
6! = 720
同理:2个0的是10,3个0的是15,4个0的是20
到此大概能发现,阶乘式中包含了几个5,结果的末尾就能有几个0
(阶乘式中的2一定比5多,所以不用担心5不能转换成10的倍数)
不过再往下继续就会发现,5个0的并不是25,而是没有数满足
原因是 5 = 5 * 5,也就是说:25是满足末尾有6个0的最小N
也就是说,5、10、15、20...,这些数中只含有一个5
而25,50,100,125...,这些数中包含多个5
那么就可以用循环除来求出一个数中包含了多少个5
static long getFive(long x){
long res=0;
while(x>0){
res = res+x/5;
x = x/5;
}
}
接下来用二分法在满足100%测试用例的范围内搜索答案即可
long整型的最大范围能满足100%测试用例
使二分查找的左起点为1,右起点为Long.MAX_VALUE-1,-1是为了避免求mid时发生溢出
import java.util.Scanner;
public class QiuJieCheng { // 求阶乘
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long k = sc.nextLong();
sc.close();
long l = 1, r = Long.MAX_VALUE - 1;
while (l < r) {
long mid = l + r >> 1;
if (getFive(mid) >= k) {
r = mid;
} else {
l = mid + 1;
}
}
if (getFive(l) == k) {
System.out.println(l);
} else {
System.out.println("-1");
}
}
static long getFive(long x) {
long res = 0;
while (x > 0) {
res = res + x / 5;
x = x / 5;
}
return res;
}
}
用时都在500ms左右,效率还不错