Data Structures & AlgorithmsHardTCS CodeVita · Microsoft SDE OA

How many trailing zeros does 100! have in base 10? Use Legendre's formula with powers of 5, counted by running the loop over p = 5, 25, 125, ...

How many trailing zeros does 100! have in base 10? Use Legendre's formula with powers of 5, counted by running the loop over p = 5, 25, 125, ...
n=100; c=0; p=5
while p<=n:
    c+=n//p; p*=5
print(c)
What is printed?
  1. A. 97
  2. B. 26
  3. C. 24
  4. D. 23

Correct answer: C. 24

Trailing zeros come from factors of 10 = 2·5, and 2s are plentiful, so the count is the power of 5 in 100!: 20 + 4 = 24, including the extra 5s in 25 and 75. Adding a term for 50 is not a power of 5, counting the 2s gives a different number, and subtracting one is an off-by-one.

More Coding Interview Problems questions

Exams that ask this topic