793. Preimage Size of Factorial Zeroes Function

2019-05-26 00:42:11 浏览数 (3)

LWC 74: 793. Preimage Size of Factorial Zeroes Function

Problem:

Let f(x) be the number of zeroes at the end of x!. (Recall that x! = 1 * 2 * 3 * … * x, and by convention, 0! = 1.) For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has 2 zeroes at the end. Given K, find how many non-negative integers x have the property that f(x) = K.

Example 1:

Input: K = 0 Output: 5 Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.

Example 2:

Input: K = 5 Output: 0 Explanation: There is no x such that x! ends in K = 5 zeroes.

Note:

  • K will be an integer in the range [0, 10^9].

思路: 考虑125!有多少个0?实际上是求1 * 2 * 3 * … * 125 有多少个5。

代码语言:javascript复制
1, 2, 3, 4, 5, ..., 125

考虑5的倍数,有
5, 10, 15, 20, ..., 125
可以得到125 / 5 = 25个5
此时剩下:
1, 2, 3, 5, ..., 25
还有5的倍数,同理得到25 / 5 = 5个5
依次类推,能够得到1 * 2 * 3 * ... * 125中5的个数。

于是:
可以求出<=K的上界 upper1
及<= K - 1的上界 upper2

ans = upper1 - upper2

Java版本:

代码语言:javascript复制
    public int preimageSizeFZF(int K) {
        return (int)(count(K) - count(K - 1));
    }

    long count(int K) {
        if (K == -1) return 0;
        long lf = 0;
        long rt = Integer.MAX_VALUE;
        while (lf < rt) {
            long mid = lf   (rt - lf   1) / 2;
            long cnt = 0;
            for (long k = mid / 5; k > 0; k /= 5) cnt  = k;
            if (cnt <= K) {
                lf = mid;
            }
            else{
                rt = mid - 1;
            }
        }
        return rt   1;
    }

0 人点赞