Factorial Trailing Zeroes - Problem
Given an integer n, return the number of trailing zeroes in n! (n factorial).
Trailing zeroes are the zeros at the end of a number. For example, 1200 has 2 trailing zeroes, while 1002 has 0 trailing zeroes.
What is a factorial?
The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n:
n! = n × (n-1) × (n-2) × ... × 3 × 2 × 1
Examples:
3! = 3 × 2 × 1 = 6→ 0 trailing zeroes5! = 5 × 4 × 3 × 2 × 1 = 120→ 1 trailing zero10! = 3,628,800→ 2 trailing zeroes
Your task: Find an efficient way to count these trailing zeroes without actually calculating the massive factorial number!
Input & Output
example_1.py — Basic case
$
Input:
n = 3
›
Output:
0
💡 Note:
3! = 6, which has no trailing zeros since 6 doesn't end with any zeros.
example_2.py — Single trailing zero
$
Input:
n = 5
›
Output:
1
💡 Note:
5! = 120, which has 1 trailing zero. This comes from the factor 5 (from 5) and factor 2 (from 2 or 4) creating one factor of 10.
example_3.py — Multiple trailing zeros
$
Input:
n = 25
›
Output:
6
💡 Note:
25! has 6 trailing zeros. We count: ⌊25/5⌋ + ⌊25/25⌋ = 5 + 1 = 6. The extra zero comes from 25 = 5², which contributes an additional factor of 5.
Constraints
- 0 ≤ n ≤ 104
- Follow-up: Could you solve this without calculating the actual factorial?
Visualization
Tap to expand
Understanding the Visualization
1
Identify the pattern
Trailing zeros = min(factors of 2, factors of 5) in n!
2
Count factors of 5
Every 5th number contributes a factor of 5
3
Account for higher powers
Every 25th number contributes an extra factor of 5
4
Sum all contributions
⌊n/5⌋ + ⌊n/25⌋ + ⌊n/125⌋ + ...
Key Takeaway
🎯 Key Insight: Since factors of 2 are always more abundant than factors of 5 in factorials, we only need to count factors of 5 to determine the number of trailing zeros.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code