793 Preimage Size of Factorial Zeroes Function
1. Question
Letf(x)
be the number of zeroes at the end ofx!
. (Recall thatx! = 1 * 2 * 3 * ... * x
, and by convention,0! = 1
.)
For example,f(3) = 0
because 3! = 6 has no zeroes at the end, whilef(11) = 2
because 11! = 39916800 has 2 zeroes at the end. GivenK
, find how many non-negative integersx
have the property thatf(x) = K
.
Note:
K
will be an integer in the range[0, 10^9]
.
2. Implementation
(1) Binary Search
思路: 题目要求的是有多少个x,满足x!的值得0的个数等于K.
通过观察我们首先知道一个数的阶乘有多少个0取决于这个的有多少个5这个因子。numOfTrailingZeroes()可以让我们知道一个数末尾有多少个0。
如果一个数的末尾有K个0结尾,那么同样有K个0结尾的数最多有5个。原因很简单,如果x有K个0结尾,那么最多有 x + 1, x + 2, x + 3, x + 4也是K个零结尾,而对于x + 5,由于其比x多了一个5的因子,所以x + 5会有K + 1零结尾。
同时可以发现f(x) 是一个非递减函数,即如果 x < y, f(x) <= f(y),这时我们想到用二分查找法找到符合条件的x,使得f(x) = K., 查找x的范围在[0, 5 * K + 5]
3. Time & Space Complexity
Binary Search: 时间复杂度O((logK)^2), numOfTrailingZeroes()需要O(logK)的时间,在[0, 5K + 5]的区间二分查找也需要O(logK)的时间。空间复杂度O(1)
Last updated
Was this helpful?