Problem
793. Preimage Size of Factorial Zeroes Function
Relevant problem
An easy problem as 172. Factorial Trailing Zeroes and its solutions: https://hezhigang.github.io/2020/06/06/LeetCode-Algorithms-factorial-trailing-zeroes/
Java
Binary Search strategy
Binary search, also known as half-interval search, logarithmic search, or binary chop, is a general algorithm for linearly ordered data structure, and There are numerous variations of binary search.
Let \( f(x) \) be the number of zeroes at the end of \(x!\). We can observe that \( f(x) \) rise when \( x \equiv 0 \hspace{2mm} (mod \hspace{1mm} 5) \),
and \( f(5k)=f(5k+1)=f(5k+2)=f(5k+3)=f(5k+4) \).
\( f(x)=\lfloor \frac{x}{5} \rfloor + \lfloor \frac{x}{25} \rfloor + \cdots + \lfloor \frac{x}{5^n} \rfloor \) where \( \lfloor \frac{x}{5^n} \rfloor \geq 1 \)
This geometric sequence with common ratio \( r = \frac{1}{5} \) has a limit that can be computed from the finite sum formula \( \sum_{k=1}^{\infty} \frac{x}{5^k} = \lim_{n \to \infty}\sum_{k=1}^{n} \frac{x}{5^k} = \frac{\frac{x}{5}}{1-\frac{1}{5}} = \frac{x}{4} \), so, there is a inequality that \( \frac{x}{5} < f(x) < \frac{x}{4} \), which gives a small upper and lower bound for binary search algorithm.
1 | class Solution { |
Submission Detail
- 44 / 44 test cases passed.
- Runtime: 0 ms, faster than 100.00% of Java online submissions for Preimage Size of Factorial Zeroes Function.
- Memory Usage: 35.6 MB, less than 100.00% of Java online submissions for Preimage Size of Factorial Zeroes Function.
Complexity Analysis
Time Complexity
\( O(NlogN) \) where N is the input integer such that \( f(x)=N \)
Space Complexity
\( O(1) \) as there is no extra space other than local varibles.