Working on an example but it does not work. There must be a function which counts trailing zero in n! the factorial formula. where, n is the number for whose factorial we want to find the number of trailing zeros. Used some imports but it did not work.
My code:
JavaScript
x
26
26
1
def is_positive_integer(x):
2
try:
3
x = float(x)
4
except ValueError:
5
return False
6
else:
7
if x.is_integer() and x > 0:
8
return True
9
else:
10
return False
11
12
13
def trailing_zeros(num):
14
if is_positive_integer(num):
15
# The above function call has done all the sanity checks for us
16
# so we can just convert this into an integer here
17
num = int(num)
18
19
k = math.floor(math.log(num, 5))
20
zeros = 0
21
for i in range(1, k + 1):
22
zeros = zeros + math.floor(num/math.pow(5, i))
23
return zeros
24
else:
25
print("Factorial of a non-positive non-integer is undefined")
26
Ex:
JavaScript
1
12
12
1
Input: n = 5
2
Output: 1
3
Factorial of 5 is 120 which has one trailing 0.
4
5
Input: n = 20
6
Output: 4
7
Factorial of 20 is 2432902008176640000 which has
8
4 trailing zeroes.
9
10
Input: n = 100
11
Output: 24
12
Output must be:
JavaScript
1
3
1
Trailing 0s in n! = Count of 5s in prime factors of n!
2
= floor(n/5) + floor(n/25) + floor(n/125) + .
3
Advertisement
Answer
This code can do the job, your code is very complex.
JavaScript
1
15
15
1
def Zeros(n):
2
count = 0
3
4
i = 5
5
while n / i >= 1:
6
count += int(n / i)
7
i *= 5
8
9
return int(count)
10
11
12
n = 100
13
print("Trailing zeros " +
14
"in 100! is", Zeros(n))
15
Output:
JavaScript
1
2
1
Trailing zeros in 100! is 24
2