SDE & MLE Prep

172. Factorial Trailing Zeroes

Problem

Return how many trailing zeros n! has.

Example: 3 → 0; 5 → 1 (5! = 120)

Constraints: n ≤ 10⁴. Follow-up: logarithmic time.

Each trailing zero needs a factor 10 = 2 · 5, and 2s are plentiful, so count factors of 5: n/5 + n/25 + n/125 + ….

Complexity: O(log n).

class Solution:
    def trailingZeroes(self, n: int) -> int:
        count = 0
        while n:
            n //= 5
            count += n
        return count