gravatar

Blog # 31 : Counting trailing Zeros in N!

You are given a number N which will be large (within limits of machine representation of long integer)
You need to find the total trailing zeros in N! (factorial)
Give attention to time complexity. Reduce it as far as possible.

Eg, 
N = 6 
N! = 720
Count = 1 (trailing means to the end)




Solution:

Keep on dividing N by 5 repeatedly and add the quotient each time until number becomes 0. The sum of all the quotients will be the number of trailing zeros.
Code:
#include<iostream>
using namespace std;
int main()
{
int N;
cin>>N;
int count = 0;
while(N > 0)
{
    count += N/5;
    N = N/5;
}
cout<<count; 
return 0;
}
Enhanced by Zemanta