Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Count trailing zeros of n! (number of factors 5).

Problem: Count trailing zeros of n! (number of factors 5).
def tz(n):
    c = 0
    while n:
        n //= 5; c += n
    return c
print(tz(25), tz(100), tz(1000))
What is printed?
  1. A. 5 20 200
  2. B. 6 24 248
  3. C. 5 24 249
  4. D. 6 24 249

Correct answer: D. 6 24 249

Each trailing zero needs a factor 10 = 2 × 5, and 2s are plentiful, so count 5s: ⌊n/5⌋ + ⌊n/25⌋ + ⌊n/125⌋ + … 25 → 5 + 1 = 6; 100 → 20 + 4 = 24; 1000 → 200 + 40 + 8 + 1 = 249. Counting only ⌊n/5⌋ misses the extra 5s in 25, 125, … O(log n).

More Coding Interview Problems questions

Exams that ask this topic