- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# C/C++ Program to Count trailing zeroes in factorial of a number?

Here we will see how to calculate the number of trailing 0s for the result of factorial of any number. So if the n = 5, then 5! = 120. There is only one trailing 0. For 20!, it will be 4 zeros as 20! = 2432902008176640000.

The easiest approach is just calculating the factorial and count the 0s. But this approach fails for large value of n. So we will follow another approach. The trailing zeros will be there, if the prime factors are 2 and 5. If we count the 2s and 5s we can get the result. For that we will follow this rule.

Trailing 0s = Count of 5s in prime factors of factorial(n)

## Algorithm

#### countTrailingZeros(n)

begin count := 0 for i := 5, (n/i) >= 1, increase i := i * 5, do count := count + (n / i) done return count; end

## Example

#include <iostream> #include <cmath> #define MAX 20 using namespace std; int countTrailingZeros(int n) { int count = 0; for (int i = 5; n / i >= 1; i *= 5) count += n / i; return count; } main() { int n = 20; cout << "Number of trailing zeros: " << countTrailingZeros(n); }

## Output

Number of trailing zeros: 4

- Related Questions & Answers
- C/C++ Programming to Count trailing zeroes in factorial of a number?
- Python Program to Count trailing zeroes in factorial of a number
- Java Program to Count trailing zeroes in factorial of a number
- Factorial Trailing Zeroes in C++
- Count trailing zeros in factorial of a number in C++
- C program to find trailing zero in given factorial
- Preimage Size of Factorial Zeroes Function in C++
- Program to find trailing zeros in factorial of n in C++?\n
- C Program to count trailing and leading zeros in a binary number
- Program for factorial of a number in C program
- Find the Number of Trailing Zeroes in Base 16 Representation of N! using C++
- Find the Number of Trailing Zeroes in base B Representation of N! using C++
- How to remove trailing zeroes in a decimal number in Java?
- Count number of trailing zeros in product of array in C++
- C++ program to Calculate Factorial of a Number Using Recursion

Advertisements