2145 求阶乘

2145 求阶乘

⭐️难度:困难
考点:2022、省赛、二分、数学

2145 求阶乘_第1张图片

import java.util.Scanner;
import java.util.Arrays;

public class Main2 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

       long k = sc.nextLong();
       long l = 1l;
       long r = Long.MAX_VALUE-1;
       while(l < r){
           long mid = (l + r) / 2;
           if(k <= calc(mid)){
               r = mid;
           } else if (k > calc(mid)) {
               l = mid + 1;
           }
       }
       if(calc(r) != k){
           System.out.println("-1");
       }else {
           System.out.println(r);
       }
    }

    static long calc(long x){
        long res = 0;
        //求阶乘末尾0的个数其实就是 求阶乘因子中5的个数
        //5!= 1 * 2 * 3 * 4 * 5 = 120
        //10! = 1 * 2 * 3 * 4 * 5 * ... * 9 * 2 * 5 = 3628800
        //15!= 1 * 2 * 3 * 4 * 5 * ... * 9 * 2 * 5 * ... * 14 * 3 * 5 = 1307674368000
        //...
        //41的阶乘因子中有9个5,25里面有两个5
        while (x != 0) {
            res = res + x / 5; //求5的个数,如果x为17时,while()循环没有结束,这里不用担心x取到17
            x /= 5;
        }
        return res;
    }
}

这题太难想了:
1️⃣首先要想到阶乘后面的0和阶乘因子中的5有关,有多少个5就有多少个0,不知道就做不出来这题。
2️⃣因为要求最小的n,所以要从大的数字开始往下推算,可是一个个减又太慢了,所以就用二分,0的数量比k大说明数字大了,右边界收缩,反之,0的数量比k小说明数字小了,左边界收缩。

你可能感兴趣的:(#,刷题,蓝桥杯)