Wednesday 3 June 2009

Finding out the number of Zeroes at the end of Factorial for a number

There is a unique formula to find out the number of zeroes at the end of a factorial of a given number.
Divide the number by power of 5s and add the sum.
For eg.
Take the number 60.
= (60/5) + (60/25 ) + (60/125) + ...
= 12 + 2 + 0 + ..
= 14.

you can stop the series once the power of 5 exceeds the number.

C++ program for the logic:

#include
#include
using namespace std;

int main()
{
int tc,i;
long int count,num5,inp;
vector output;
cin>>tc;
for(i=0;i>inp;
num5=5;
count=0;
while(inp >= num5)
{
count += inp / num5;
num5*=5;
}
output.push_back(count);
}
for(i=0;i
cout<<
//system("pause");
return 0;
}

No comments: