Let's compute :
def fact(n):
res = 1
for i in range(1, n+1):
res *= i
return res
fact(500)
Suppose we'd like to count up the number of trailing zeros in -- the zeros at the end of the number. Here is the strategy:
(Note that dividing a number by 10 is the same as removing one trailing zero.)
def trailing_zeros(n):
fact_n = fact(n)
counter = 0
while fact_n % 10 == 0:
fact_n //= 10
counter += 1
return counter
trailing_zeros(500)
We have set up a counter variable, which is incremented every time we divide fact_n
by 10 (i.e., remove a trailing 0.
What happens if n! has no trailing 0s? We simply never enter the while
-loop, and return 0, which is the correct thing.