### Finding the Number of Trailing Zero's in Factorial of a Number

Factorial of a number is one of the most basic sums that you'll be doing whenever you learn a programming language. Finding the number of trailing zero's in the factorial of a number sounds pretty simple right ? You can just find the factorial of the number and you can run a while loop until factorial % 10 == 0 and increment a counter.

But it doesn't work like that. There is no data type in C which can hold the factorial of 21 or greater. So you cannot simply find the factorial and find the number of zero's. The solution for the problem is pretty simple. You can just find the number of two's and number of five's (5 x 2 = 10) in every number that constitutes the factorial and return the number of five's. That's it. Sounds very simple right ? Yes it is.

Feel free to post your doubts below :)

But it doesn't work like that. There is no data type in C which can hold the factorial of 21 or greater. So you cannot simply find the factorial and find the number of zero's. The solution for the problem is pretty simple. You can just find the number of two's and number of five's (5 x 2 = 10) in every number that constitutes the factorial and return the number of five's. That's it. Sounds very simple right ? Yes it is.

**Program**

- #include <iostream>
- using namespace std;
- int zeros(int A){
- int two = 0;
- int five = 0;
- int temp;
- for(int i = 2; i <= A; i++){
- temp = i;
- while(temp % 2 == 0 || temp % 5 == 0){
- if(temp % 2 == 0){
- two++;
- temp = temp / 2;
- }
- if(temp % 5 == 0){
- five++;
- temp = temp / 5;
- }
- }
- }
- return ((two > five) ? five : two);
- }
- int main(int argc, const char * argv[]) {
- cout<<zeros(100);
- return 0;
- }

Feel free to post your doubts below :)

## Comments

## Post a Comment