Write a Python program to determine $f(n)$, the number of trailing zeros in $n!$, using the special case of de Polignac's formula:
$$
f(n) = \sum_{i=1} \left\lfloor \frac{n}{5^i} \right\rfloor,
$$
where $\lfloor x \rfloor$ denotes the floor of $x$, the largest integer less than or equal to $x$.
Solution P2.5.6
Here is one solution:
# Caculate the number of trailing zeros in n! using de Polignac's formula:
# nzeros = sum_i floor(n/5^i)
import math
n = 126
nzeros = 0
term = n
while True:
term //= 5
if term == 0:
break
nzeros += term
print('{:d}! ends in {:d} zeros.'.format(n, nzeros))
print('{:d}! = {:d}'.format(n, math.factorial(n)))
For this example value of n the output is:
126! ends in 31 zeros.
126! = 23721732428800468856771473051394170805702085973808045661837377170052497697783313457227249544076486314839447086187187275319400401837013955325179315652376928996065123321190898603130880000000000000000000000000000000