Python Program to Count trailing zeroes in factorial of a number
Last Updated :
09 Mar, 2023
Given an integer n, write a function that returns the count of trailing zeroes in n!
Examples :
Input: n = 5
Output: 1
Factorial of 5 is 120 which has one trailing 0.
Input: n = 20
Output: 4
Factorial of 20 is 2432902008176640000 which has
4 trailing zeroes.
Input: n = 100
Output: 24
Trailing 0s in n! = Count of 5s in prime factors of n!
= floor(n/5) + floor(n/25) + floor(n/125) + ....
Method 1:
Python3
# Python3 program to
# count trailing 0s
# in n !
# Function to return
# trailing 0s in
# factorial of n
def findTrailingZeros(n):
# Initialize result
count = 0
# Keep dividing n by
# powers of 5 and
# update Count
i = 5
while (n / i >= 1):
count += int(n / i)
i *= 5
return int(count)
# Driver program
n = 100
print("Count of trailing 0s " +
"in 100 ! is", findTrailingZeros(n))
Output:Count of trailing 0s in 100 ! is 24
Time Complexity: O(log5n)
Auxiliary Space: O(1)
Please refer complete article on Count trailing zeroes in factorial of a number for more details!
Method 2: Using math.factorial() and for loop
Python3
# Python3 program to
# count trailing 0s
# in n !
# Function to return
# trailing 0s in
# factorial of n
def findTrailingZeros(n):
import math
c = 0
x = math.factorial(n)
s = str(x)
a = s[::-1]
for i in a:
if(i != "0"):
break
else:
c += 1
return c
# Driver program
n = 100
print("Count of trailing 0s " +
"in 100 ! is", findTrailingZeros(n))
OutputCount of trailing 0s in 100 ! is 24
Time complexity: O(n)
Space complexity: O(n)
Method 3: Using recursion
Follow the steps below:
- The function countTrailingZeroes takes the parameter n and a count variable count which is initialized to 0.
- If n is equal to 0, the function returns the count variable. This is because there are no more numbers to check for multiples of 5.
- If n is not equal to 0, the function updates the count variable by dividing n by 5 and adding the result to the count variable.
- The function then calls itself, this time with n divided by 5 and the updated count variable as parameters.
- The main function initializes the n variable and calls the countTrailingZeroes function, storing the result in the result variable.
- Finally, the main function prints out the number of trailing zeros in n!.
Python3
def countTrailingZeroes(n, count = 0):
if n == 0:
return count
else:
count += n//5
return countTrailingZeroes(n//5, count)
def main():
n = 100
result = countTrailingZeroes(n)
print("The number of trailing zeros in %d! is %d" % (n, result))
if __name__ == '__main__':
main()
OutputThe number of trailing zeros in 100! is 24
Time complexity: O(log n). This is because in each recursive call, the value of n is divided by 5 until it becomes 0. Hence, the number of recursive calls is proportional to log n to the base 5.
Auxiliary space: O(log n) as well, because of the number of function calls required for the recursive function.
Method 4: Using Iterative method
Use a while loop to count the number of multiples of 5, starting from 5, and then multiplies the current count by 5 to count the next power of 5. The loop continues until the current power of 5 is greater than n. Finally, the function returns the total count of powers of 5, which corresponds to the number of trailing zeros in n!.
Python3
import math
def findTrailingZeros(n):
# count powers of 5 in prime factorization
trailing_zeros = 0
i = 5
while i <= n:
trailing_zeros += n // i
i *= 5
return trailing_zeros
# Driver program
n = 100
print("Count of trailing 0s " +
"in 100 ! is", findTrailingZeros(n))
OutputCount of trailing 0s in 100 ! is 24
Time complexity: O(log n)
Auxiliary space: O(1)
Similar Reads
Python Program for Number of elements with odd factors in given range Given a range [n,m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples: Input : n = 5, m = 100 Output : 8 The numbers with odd factors are 9, 16, 25, 36, 49, 64, 81 and 100 Input : n = 8, m = 65 Output : 6 Input : n = 10, m = 23500 Output :
2 min read
Python Program to Count number of binary strings without consecutive 1's Write a Python program for a given positive integer N, the task is to count all possible distinct binary strings of length N such that there are no consecutive 1s. Examples: Input: N = 2Output: 3// The 3 strings are 00, 01, 10 Input: N = 3Output: 5// The 5 strings are 000, 001, 010, 100, 101 Recomme
4 min read
How to Create Array of zeros using Numpy in Python numpy.zeros() function is the primary method for creating an array of zeros in NumPy. It requires the shape of the array as an argument, which can be a single integer for a one-dimensional array or a tuple for multi-dimensional arrays. This method is significant because it provides a fast and memory
4 min read
How to find the factorial os a number using SciPy in Python? SciPy is an open-source Python library used to solve scientific and mathematical problems. It is built on NumPy and it allows us to manipulate and visualizing with a wide range of high-level commands. Scipy also provides a scipy.special.factorial() function to calculate factorial of any number. scip
2 min read
How to Add leading Zeros to a Number in Python In this article, we will learn how to pad or add leading zeroes to the output in Python. Example:Input: 11 Output: 000011 Explanation: Added four zeros before 11(eleven).Display a Number With Leading Zeros in PythonAdd leading Zeros to numbers using format() For more effective handling of sophistica
3 min read
Python Bin | Count total bits in a number Given a positive number n, count total bit in it. Examples: Input : 13 Output : 4 Binary representation of 13 is 1101 Input : 183 Output : 8 Input : 4096 Output : 13 We have existing solution for this problem please refer Count total bits in a number link. Approach#1: We can solve this problem quick
3 min read
Move All Zeroes to End of Array using List Comprehension in Python We will solve this problem in python using List Comprehension in a single line of code. This allows us to create a new list by iterating over an existing list in a concise and efficient manner. We can utilize list comprehension to separate the non-zero elements and zeros, then combine them together
2 min read
Reverse bits of a positive integer number in Python Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this pr
4 min read
Count the Number of Null Elements in a List in Python In data analysis and data processing, It's important to know about Counting the Number of Null Elements. In this article, we'll explore how to count null elements in a list in Python, along with three simple examples to illustrate the concept. Count the Number of Null Elements in a List in PythonIn
3 min read
How to convert string to integer in Python? In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equiv
3 min read