Factorial Trailing Zeroes - Problem

Given an integer n, return the number of trailing zeroes in n!.

Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.

Follow up: Could you write a solution that works in logarithmic time complexity?

Input & Output

Example 1 — Small Factorial
$ Input: n = 3
Output: 0
💡 Note: 3! = 6, which has no trailing zeros
Example 2 — One Trailing Zero
$ Input: n = 5
Output: 1
💡 Note: 5! = 120, which has 1 trailing zero (from 2×5=10)
Example 3 — Multiple Zeros
$ Input: n = 25
Output: 6
💡 Note: 25! has 6 trailing zeros from factors: 5 multiples of 5 plus 1 extra from 25=5×5

Constraints

  • 0 ≤ n ≤ 104

Visualization

Tap to expand
Factorial Trailing Zeroes INPUT n = 3 Integer input 3! = 3 x 2 x 1 3 x 2 x 1 = 6 Input Values: n = 3 Find trailing 0s in 3! ALGORITHM STEPS 1 Count factors of 5 Trailing 0 = pairs of 2 x 5 2 Formula: n/5 + n/25... Sum n/5^k while 5^k <= n 3 Apply to n=3 3/5 = 0 (integer div) 4 Sum all counts Result = 0 Calculation: count = 0 n = 3 3 / 5 = 0 Total = 0 FINAL RESULT 3! = 6 6 No trailing zeros! Compare: 5! = 120 --> 1 zero 10! = 3628800 --> 2 3! = 6 --> 0 zeros Output: 0 OK - Verified Key Insight: Trailing zeros come from factors of 10 = 2 x 5. Since 2s are abundant, we only count 5s. Formula: count = n/5 + n/25 + n/125 + ... (O(log n) time complexity) For n=3: 3/5 = 0, so there are 0 trailing zeros in 3! = 6 TutorialsPoint - Factorial Trailing Zeroes | Optimal Solution (Logarithmic Time)
Asked in
Microsoft 35 Amazon 28 Apple 22 Google 18
85.0K Views
Medium Frequency
~15 min Avg. Time
3.2K 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