Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Program to find trailing zeros in factorial of n in C++?\\n
Suppose we have a number n, we have to find the number of trailing zeros of n!.
So, if the input is like n = 20, then the output will be 4, as 20! = 2432902008176640000
To solve this, we will follow these steps
set count := 0
-
for i := 5, (n/i) > 1, update i := i * 5, do
count := count + (n /i)
return count
Let us see the following implementation to get better understanding
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);
}
Input
20
Output
Number of trailing zeros: 4
Advertisements