Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the number of trailing zeros of 1000!?

Problem: What is the number of trailing zeros of 1000!?
n = 1000
c = 0
p = 5
while p <= n:
    c += n // p
    p *= 5
print(c)
What is printed?
  1. A. 200
  2. B. 240
  3. C. 250
  4. D. 249

Correct answer: D. 249

Legendre's formula counts factors of 5 in 1000!: 200 + 40 + 8 + 1 = 249, and factors of 2 are always plentiful. Stopping after 1000 // 5 gives 200, after the 25-term gives 240, and the shortcut n / 4 = 250 overcounts because the floors lose fractions.

More Coding Interview Problems questions

Exams that ask this topic