LeetCode 172 · Bits · Math

Factorial Trailing Zeroes, explained with a picture

Counting pairs of shoes that make tens.

Bits · Math
▶ Watch it step by step

The problem

Count the trailing zeros of n! (n factorial).

Input:  n = 26
Output: 6

Picture it

Picture each trailing zero as a 10 = 2 × 5. There are always more 2s than 5s, so count the 5s: multiples of 5 give one each, multiples of 25 an extra one, and so on.

Short version: the full lesson (brute force, complexity, edge cases and a quiz) is still being written. The animation is complete.

The key idea

Sum n // 5 + n // 25 + n // 125 + … O(log n).

Python solution

def trailing_zeroes(n):
    count = 0
    while n:
        n //= 5                  # multiples of 5, then 25, 125…
        count += n
    return count

In the interactive version each line lights up as the animation runs, and you can type your own input to see the algorithm handle it.