1. 题目
f(x) 是 x! 末尾是0的数量。(回想一下 x! = 1 * 2 * 3 * ... * x,且0! = 1
)
例如, f(3) = 0 ,因为3! = 6的末尾没有0;而 f(11) = 2 ,因为11!= 39916800末端有2个0。给定 K,找出多少个非负整数x ,有 f(x) = K 的性质。
示例 1:
输入:K = 0
输出:5
解释: 0!, 1!, 2!, 3!, and 4! 均符合 K = 0 的条件。示例 2:
输入:K = 5
输出:0
解释:没有匹配到这样的 x!,符合K = 5 的条件。注意:
K是范围在 [0, 10^9] 的整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/preimage-size-of-factorial-zeroes-function
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
程序员面试金典 - 面试题 16.05. 阶乘尾数(5的因子)
2.1 二分查找
class Solution {
public:int preimageSizeFZF(int K) {return binsearch(K+1)-binsearch(K);}int tail0count(long n)//计算尾0的个数{int count = 0;while(n){count += n/5;n /= 5;}return count;}int binsearch(int K)//查找阶乘有K个0的最小数{long l = 0, r = 1e10, mid, count0;while(l < r){mid = l+((r-l)>>1);count0 = tail0count(mid);if(count0 < K)l = mid+1;else// if(count0 >= K)r = mid;}return l;}
};
2.2 数学解
阶乘尾0个数跟因子5有关,数字每增加5,尾0个数至少增加1,所以答案不是5个就是0个
参考题解区:数学推导