Skip to content
scipython.com

P2.5.6de Polignac's formula

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\).

Show solution

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! = 2372173242880046885677147305139417080570208597380804566183737717005249769778331345722724
954407648631483944708618718727531940040183701395532517931565237692899606512332119089860313088
0000000000000000000000000000000