Problem Description
Given an integer n, return the number of trailing zeroes in n! (n factorial). The trailing zeroes are caused by the factors 10, which come from multiplying 2 and 5. Since there are more factors of 2 than 5 in n!, the number of trailing zeroes is determined by the number of times 5 is a factor in the numbers from 1 to n.
Key Insights
- Trailing zeroes are produced by factors of 10 (2 * 5) in the factorial.
- There are more 2s than 5s in n! so counting the number of 5 factors will suffice.
- Count how many multiples of 5, 25, 125, etc., since each contributes additional factors of 5.
- This approach runs in logarithmic time relative to n.
Space and Time Complexity
Time Complexity: O(log n)
Space Complexity: O(1)
Solution
We count the factors of 5 in n! by repeatedly dividing n by 5. The intuition is that every 5th number contributes at least one factor of 5, every 25th contributes an extra factor because 25 = 5*5, and so on. We continue this division until n becomes 0. This avoids computing the factorial directly, providing a very efficient solution. The algorithm uses a simple loop and integer division, resulting in logarithmic time complexity and constant space usage.