leetcode#793. Preimage Size of Factorial Zeroes Function

793. Preimage Size of Factorial Zeroes Function

Problem Description

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.

Analysis

To begin with, we can infer that the result is either 0 or 5. We just need to judge if the input K is valid, which depends on how many 5 in x!. In convenience, we transform x into x / 5 and find the proper x such that f(x) = k.

Calculating the original x from K inversely seems not easy. However, we can write up the formula to calculate K from a given x. Here is the formula and the algorithm:

Formula:

k = x + x / 5 + x / 25 + x / 125 + ...

Algorithm:

f(x) = 
    k <- x
    while x / 5 > 0
        x <- x / 5
        k <- k + x
    return k

Then we can estimate the range of x, which is smaller than K and larger than 4K/5. So we just need to iterate from 4K/5 to K and find the right x to check whether the K is valid. However, the time cost is a little expensive, so we should use binary search to speed up. Finally, we can write the full code as below.

Code

class Solution {
public:
    int preimageSizeFZF(int K) {
        int low = K * 4 / 5;
        int high = K;
        while (high - low > 1) {
            int mid = (low + high) / 2;
            int tmp = f(mid);
            if (tmp == K) return 5;
            if (tmp < K) {
                low = mid;
            } else {
                high = mid;
            }            
        }

        if (f(high) == K || f(low) == K) return 5;
        return 0;
    }

    int f(int x) {
        int k = x % 5;
        while (x / 5) {
            x /= 5;
            k += x * 5 + x % 5;
        }
        return k;
    }
};

你可能感兴趣的:(leetcode)