CodingNodes / Math & Geometry / Factorial Trailing Zeroes System design Space play · ←→ step · R restart

Problem

Given a non-negative integer n, return how many zeros sit at the end of n! (that is, 1 × 2 × 3 × … × n).

Do not compute the factorial itself; it grows far too fast.

Constraints

  • 0 ≤ n ≤ 10⁴

Examples: pick one to animate

Solutions

TimeO(log n) SpaceO(1)

Time: n is divided by 5 each round, so there are about log base 5 of n rounds.

Space: Only n and count are stored.

A trailing zero needs a factor of 10 = 2 × 5, and there are always more 2s than 5s. So count the 5s in n!: n / 5 numbers give one, n / 25 give a second, n / 125 a third, and so on. Dividing n by 5 again and again and adding each quotient does exactly that.