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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值