Preimage Size of Factorial Zeroes Function - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: k = 3
Output: 5
💡 Note: f(15) = f(16) = f(17) = f(18) = f(19) = 3, so exactly 5 numbers give 3 trailing zeros
Example 2 — Special Case Zero
$ Input: k = 0
Output: 5
💡 Note: f(0) = f(1) = f(2) = f(3) = f(4) = 0, so exactly 5 numbers give 0 trailing zeros
Example 3 — Impossible Value
$ Input: k = 4
Output: 5
💡 Note: f(20) = f(21) = f(22) = f(23) = f(24) = 4, so exactly 5 numbers give 4 trailing zeros

Constraints

  • 0 ≤ k ≤ 109

Visualization

Tap to expand
Preimage Size of Factorial Zeroes INPUT f(x) = trailing zeros in x! x! examples: 3! = 6 f(3)=0 5! = 120 f(5)=1 10! = 3628800 f(10)=2 11! = 39916800 f(11)=2 15! = ...000 f(15)=3 19! = ...0000 f(19)=3 20! = ...0000 f(20)=4 Input: k = 3 Find count of x where f(x) = k ALGORITHM STEPS 1 Count Zeros Formula f(x)=x/5+x/25+x/125+... 2 Binary Search Find smallest x: f(x)>=k 3 Check Validity If f(x)!=k, return 0 4 Return Result Always 0 or 5 f(x) for x = 15 to 24: 15 16 17 18 19 20 3 3 3 3 3 4 f(x)=3 for x in {15,16,17,18,19} Count = 5 FINAL RESULT Values x where f(x) = 3: 15 16 17 18 19 Output: 5 Verification: 15!/5 + 15!/25 = 3+0 = 3 20!/5 + 20!/25 = 4+0 = 4 OK - Count is 5 Key Insight: Trailing zeros come from factors of 10 = 2*5. Since 2s are more common, count 5s: f(x) = x/5 + x/25 + x/125 + ... f(x) increases by 1 for each multiple of 5, but jumps by 2+ at 25, 125, etc. Answer is always 0 or 5. TutorialsPoint - Preimage Size of Factorial Zeroes Function | Binary Search Approach
Asked in
Google 15 Microsoft 8
12.0K Views
Medium Frequency
~25 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen