#793
Hard Algorithms Preimage size of factorial zeroes function
Math Binary Search
46.7% acceptance
Feb 21, 2026
471
104
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.
Solution
Rust
Time O(n log n)
Space O(n)
/*
* 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 <= 109
*/
impl Solution {
pub fn preimage_size_fzf(k: i32) -> i32 {
fn trailing_zeros(x: i64) -> i64 {
let mut count = 0i64;
let mut p = 5i64;
while p <= x { count += x / p; p *= 5; }
count
}
fn count_le(k: i64) -> i64 {
if k < 0 { return 0; }
let mut lo = 0i64;
let mut hi = 5 * (k + 1);
while lo < hi {
let mid = lo + (hi - lo) / 2;
if trailing_zeros(mid) <= k { lo = mid + 1; } else { hi = mid; }
}
lo
}
let k = k as i64;
(count_le(k) - count_le(k - 1)) as i32
}
}