#!/usr/bin/env python # coding: utf-8 # ### Factorials # # Let's compute $n! = 1\times 2\times 3\times 4....\times n$: # In[1]: def fact(n): res = 1 for i in range(1, n+1): res *= i return res # In[2]: fact(500) # ### Trailing zeros # # Suppose we'd like to count up the number of *trailing zeros* in $n!$ -- the zeros at the end of the number. Here is the strategy: # # * Compute fact_n = n! # * Keep dividing fact_n by 10 while it's divisible by 10 # * The number of times that res could be divided by 10 is the number of trailing zeros in n! # # (Note that dividing a number by 10 is the same as removing one trailing zero.) # In[3]: def trailing_zeros(n): fact_n = fact(n) counter = 0 while fact_n % 10 == 0: fact_n //= 10 counter += 1 return counter # In[4]: 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.