Open In App

# Count trailing zeroes in factorial of a number

Given an integer n, write a function that returns count of trailing zeroes in n!.
Examples :

`Input: n = 5Output: 1 Factorial of 5 is 120 which has one trailing 0.Input: n = 20Output: 4Factorial of 20 is 2432902008176640000 which has4 trailing zeroes.Input: n = 100Output: 24`

## We strongly recommend that you click here and practice it, before moving on to the solution.

1. Approach:
A simple method is to first calculate factorial of n, then count trailing 0s in the result (We can count trailing 0s by repeatedly dividing the factorial by 10 till the remainder is not 0).

2. The above method can cause overflow for slightly bigger numbers as the factorial of a number is a big number (See factorial of 20 given in above examples). The idea is to consider prime factors of a factorial n. A trailing zero is always produced by prime factors 2 and 5. If we can count the number of 5s and 2s, our task is done. Consider the following examples.
n = 5: There is one 5 and 3 2s in prime factors of 5! (2 * 2 * 2 * 3 * 5). So a count of trailing 0s is 1.
n = 11: There are two 5s and eight 2s in prime factors of 11! (2 8 * 34 * 52 * 7). So the count of trailing 0s is 2.

3. We can easily observe that the number of 2s in prime factors is always more than or equal to the number of 5s. So if we count 5s in prime factors, we are done. How to count the total number of 5s in prime factors of n!? A simple way is to calculate floor(n/5). For example, 7! has one 5, 10! has two 5s. It is not done yet, there is one more thing to consider. Numbers like 25, 125, etc have more than one 5. For example, if we consider 28! we get one extra 5 and the number of 0s becomes 6. Handling this is simple, first, divide n by 5 and remove all single 5s, then divide by 25 to remove extra 5s, and so on. Following is the summarized formula for counting trailing 0s.
`Trailing 0s in n! = Count of 5s in prime factors of n!                  = floor(n/5) + floor(n/25) + floor(n/125) + ....`

Following is a program based on the above formula:

## C++

 `// C++ program to count``// trailing 0s in n!``#include ``using` `namespace` `std;` `// Function to return trailing``// 0s in factorial of n``int` `findTrailingZeros(``int` `n)``{``    ``if` `(n < 0) ``// Negative Number Edge Case``        ``return` `-1;` `    ``// Initialize result``    ``int` `count = 0;` `    ``// Keep dividing n by powers of``    ``// 5 and update count``    ``for` `(``int` `i = 5; n / i >= 1; i *= 5)``        ``count += n / i;` `    ``return` `count;``}` `// Driver Code``int` `main()``{``    ``int` `n = 100;``    ``cout << ``"Count of trailing 0s in "` `<< 100 << ``"! is "``         ``<< findTrailingZeros(n);``    ``return` `0;``}`

## Java

 `// Java program to count``// trailing 0s in n!``import` `java.io.*;` `class` `GFG {``    ``// Function to return trailing``    ``// 0s in factorial of n``    ``static` `int` `findTrailingZeros(``int` `n)``    ``{``        ``if` `(n < ``0``) ``// Negative Number Edge Case``            ``return` `-``1``;` `        ``// Initialize result``        ``int` `count = ``0``;` `        ``// Keep dividing n by powers``        ``// of 5 and update count``        ``for` `(``int` `i = ``5``; n / i >= ``1``; i *= ``5``)``            ``count += n / i;` `        ``return` `count;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `n = ``100``;``        ``System.out.println(``"Count of trailing 0s in "` `+ n``                           ``+ ``"! is "``                           ``+ findTrailingZeros(n));``    ``}``}` `// This code is contributed by Pramod Kumar`

## Python3

 `# Python3 program to``# count trailing 0s``# in n!` `# Function to return``# trailing 0s in``# factorial of n`  `def` `findTrailingZeros(n):``    ``# Negative Number Edge Case``    ``if``(n < ``0``):``        ``return` `-``1` `    ``# Initialize result``    ``count ``=` `0` `    ``# Keep dividing n by``    ``# 5 & update Count``    ``while``(n >``=` `5``):``        ``n ``/``/``=` `5``        ``count ``+``=` `n` `    ``return` `count`  `# Driver program``n ``=` `100``print``(``"Count of trailing 0s "` `+``      ``"in 100! is"``, findTrailingZeros(n))` `# This code is contributed by Uttam Singh`

## C#

 `// C# program to count``// trailing 0s in n!``using` `System;` `class` `GFG``{``    ` `    ``// Function to return trailing``    ``// 0s in factorial of n``    ``static` `int` `findTrailingZeros(``int` `n)``    ``{``      ` `          ``if``(n < 0) ``//Negative Number Edge Case``              ``return` `-1;       ``      ` `        ``// Initialize result``        ``int` `count = 0;` `        ``// Keep dividing n by powers``        ``// of 5 and update count``        ``for` `(``int` `i = 5; n / i >= 1; i *= 5)``            ``count += n / i;` `        ``return` `count;``    ``}``    ` `    ``// Driver Code``    ``public` `static` `void` `Main ()``    ``{``        ``int` `n = 100;``        ``Console.WriteLine(``"Count of trailing 0s in "` `+``                                           ``n +``"! is "``+``                                ``findTrailingZeros(n));``    ``}``}` `// This code is contributed by vt_m`

## Javascript

 ``

## PHP

 `= 1; ``\$i` `*= 5)``        ``\$count` `+= ``\$n` `/ ``\$i``;` `    ``return` `\$count``;``}` `// Driver Code` `\$n` `= 100;``echo` `"Count of trailing 0s in "` `, 100,``     ``"! is "` `, findTrailingZeros(``\$n``);` `// This code is contributed by vt_m``?>`

Output

```Count of trailing 0s in 100! is 24
```

Time Complexity: O(log5n)

Auxiliary Space: O(1)

Approach 2 :- Counting the number of factors of 10 Another way to count the number of trailing zeroes in the factorial of a number is to count the number of factors of 10 in that number’s factorial. This is because a trailing zero is added to the factorial every time a factor of 10 is encountered.

Start the program by including the required header files and the standard namespace.

Define a function named countTrailingZeroes that takes an integer n as input and returns an integer.

Initialize a variable named count to 0, which will be used to count the number of trailing zeroes.

Create a loop that iterates from 1 to n. This loop will be used to calculate the factorial of n.

Within the loop, initialize a variable named j to the current loop variable i.

Create another loop that continues until j is no longer divisible by 5. This inner loop is used to count the number of 5s in the prime factorization of i.

Within the inner loop, increment the count variable and divide j by 5 until j is no longer divisible by 5.

Return the count variable once the loop completes.

Define the main function, which sets n equal to 100 and outputs the result of countTrailingZeroes(n).

End the program by returning 0 from the main function.

In summary, this program calculates the number of trailing zeroes in the factorial of n by counting the number of factors of 5 in the prime factorization of each number from 1 to n.

## C++

 `#include ``using` `namespace` `std;` `int` `countTrailingZeroes(``int` `n)``{``    ``int` `count = 0;``    ``for` `(``int` `i = 1; i <= n; i++) {``        ``int` `j = i;``        ``while` `(j % 5 == 0) {``            ``count++;``            ``j /= 5;``        ``}``    ``}``    ``return` `count;``}` `int` `main()``{``    ``int` `n = 100;``    ``cout << countTrailingZeroes(n) << endl;``    ``return` `0;``}`

## Java

 `public` `class` `Main {``    ``public` `static` `int` `countTrailingZeroes(``int` `n)``    ``{``        ``int` `count = ``0``;``        ``for` `(``int` `i = ``1``; i <= n; i++) {``            ``int` `j = i;``            ``while` `(j % ``5` `== ``0``) {``                ``count++;``                ``j /= ``5``;``            ``}``        ``}``        ``return` `count;``    ``}` `    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `n = ``100``;``        ``System.out.println(countTrailingZeroes(n));``    ``}``}``// This code is contributed by Prajwal Kandekar`

## Python3

 `def` `countTrailingZeroes(n):``    ``# Initialize a counter to keep track of the number of trailing zeroes.``    ``count ``=` `0` `    ``# Loop through each number from 1 to n.``    ``for` `i ``in` `range``(``1``, n``+``1``):` `        ``# Initialize a variable j to i.``        ``j ``=` `i` `        ``# While j is divisible by 5, increment the counter and divide j by 5.``        ``while` `j ``%` `5` `=``=` `0``:``            ``count ``+``=` `1``            ``j ``/``/``=` `5` `    ``return` `count`  `n ``=` `100``print``(countTrailingZeroes(n))`

## C#

 `using` `System;` `class` `GFG {` `    ``static` `int` `countTrailingZeroes(``int` `n)``    ``{``        ``// Initialize a counter to keep track of the number``        ``// of trailing zeroes.``        ``int` `count = 0;` `        ``// Loop through each number from 1 to n.``        ``for` `(``int` `i = 1; i <= n; i++) {` `            ``// Initialize a variable j to i.``            ``int` `j = i;` `            ``// While j is divisible by 5, increment the``            ``// counter and divide j by 5.``            ``while` `(j % 5 == 0) {``                ``count += 1;``                ``j /= 5;``            ``}``        ``}` `        ``return` `count;``    ``}` `    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``int` `n = 100;``        ``Console.WriteLine(countTrailingZeroes(n));``    ``}``}`

## Javascript

 `function` `countTrailingZeroes(n) {``    ``// Initialize a counter to keep track of the number of trailing zeroes.` `  ``let count = 0;``      ``// Loop through each number from 1 to n.` `  ``for` `(let i = 1; i <= n; i++) {``          ``// Initialize a variable j to i.` `    ``let j = i;``     ``//While j is divisible by 5, increment the counter and divide j by 5.` `    ``while` `(j % 5 === 0) {``      ``count++;``      ``j = Math.floor(j / 5);``    ``}``  ``}``  ``return` `count;``}` `let n = 100;``console.log(countTrailingZeroes(n));`

Output

```24
```

Time Complexity: O(n*log5n)

Auxiliary Space: O(1)