Preimage Size Of Factorial Zeroes Function Problem
Description
LeetCode Problem 793.
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 two zeroes at the end.
Given an integer k, return the number of 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.
Example 3:
Input: k = 3
Output: 5
Constraints:
- 0 <= k <= 10^9
Solution
Approach: Binary Search on the Number of Zeroes
Trailing zeroes come from factors 10 = 2 · 5, and among 1..x there are always more factors 2 than 5, so f(x) is the number of factors 5 in x!:
f(x) = x/5 + x/25 + x/125 + ... (integer division)
Two facts make the problem small:
fnever decreases asxgrows, so thexwithf(x) = kform one contiguous range.fonly changes whenxreaches a multiple of 5, so that range is a whole block5m, 5m + 1, ..., 5m + 4. The answer is therefore either 5 or 0. It is 0 whenfjumps overk: atx = 25,fgoes from 4 straight to 6, because 25 contributes two factors 5, so noxhasf(x) = 5.
Let first(k) be the smallest x with f(x) >= k. The x with f(x) = k are exactly those in [first(k), first(k + 1)), so the answer is first(k + 1) - first(k). Find first(k) by binary search over x in [0, 5k]; the upper bound is safe because f(5k) >= k.
The detail people get wrong is the range of the search: 5 · (k + 1) is about 5 · 109, which overflows a 32-bit integer, so Java and C++ search with 64-bit values.
Complexity: O(log2 k) time, since the binary search takes O(log k) steps and each f(x) takes O(log x), and O(1) space.
class Solution:
def preimageSizeFZF(self, k: int) -> int:
# The x with f(x) == k are exactly the x in [first(k), first(k + 1)).
return self.first_with_at_least(k + 1) - self.first_with_at_least(k)
def first_with_at_least(self, k: int) -> int:
"""The smallest x with f(x) >= k. f is non-decreasing, so binary search works."""
low, high = 0, 5 * k # f(5k) >= k, so the answer is at most 5k
while low < high:
mid = (low + high) // 2
if self.trailing_zeros(mid) >= k:
high = mid
else:
low = mid + 1
return low
def trailing_zeros(self, x: int) -> int:
"""f(x): every factor 5 in 1..x pairs with a factor 2 to make one trailing zero."""
zeros = 0
while x > 0:
x //= 5
zeros += x # multiples of 5, then of 25, then of 125, ...
return zeros
Now write it from memory
Close the write-up and solve it yourself against the tests.