- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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++ Programming to Count trailing zeroes in factorial of a number?
Counting the number of trailing zeroes in a factorial number is done by counting the number of 2s and 5s in the factors of the number. Because 2*5 gives 10 which is a trailing 0 in the factorial of a number.
Example
Factorial of 7 = 5040, the number of trailing 0’s is 1.
Based on our logic 7! = 2*3*4*5*6*7, it has 3 2s and 1 5s so the number of trailing 0’s is 1.
#include <iostream> using namespace std; int main() { int n = 45; int count = 0; for (int i = 5; n / i >= 1; i *= 5) count += n / i; cout<<"No of trailing 0s in " << n<< "! is " << count; return 0; }
Output
No of trailing 0s in 24! is 10
Advertisements