@@ -6,6 +6,7 @@ Number of trailing zeros in the factorial of an integer
66:slug: trailing-zeros-factorial
77:summary: Use Python to find the number of trailing zeros in the factorial of an integer
88
9+ Please note, the math expressions are broken. I will be fixing it soon.
910
1011Hi all, I recently learned about a cool formula to calculate the number of
1112trailing zeros in the factorial of a number. It has been a while since I
@@ -35,4 +36,45 @@ The key bit there in is this formula:
3536
3637 where, ``n `` is the number for whose factorial we want to find the number of trailing zeros in and ``k ``
3738
39+ The following Python program implements the above formula:
40+
41+ .. code ::
42+
43+ import math
44+
45+
46+ def is_positive_integer(x):
47+ try:
48+ x = float(x)
49+ except ValueError:
50+ return False
51+ else:
52+ if x.is_integer() and x > 0:
53+ return True
54+ else:
55+ return False
56+
57+
58+ def trailing_zeros(num):
59+ if is_positive_integer(num):
60+ # The above function call has done all the sanity checks for us
61+ # so we can just convert this into an integer here
62+ num = int(num)
63+
64+ k = math.floor(math.log(num, 5))
65+ zeros = 0
66+ for i in range(1, k + 1):
67+ zeros = zeros + math.floor(num/math.pow(5, i))
68+ return zeros
69+ else:
70+ print("Factorial of a non-positive integer is undefined")
71+
72+
73+ if __name__ == "__main__":
74+ fact_num = input(
75+ "Enter the number whose factorial's trailing zeros you want to find: "
76+ )
77+ num_zeros = trailing_zeros(fact_num)
78+ print("Number of trailing zeros: {0}".format(num_zeros))
79+
3880
0 commit comments