Tuesday, October 7, 2008

Given a number 'n'. Find the number of trailing zeros in n factorial.

Technique:
Number of Trailing zeros = floor(num / 5) + floor(num / 5^2) + floor(num / 5^3) + ....

#include <>
using namespace std;
void main()
{
int n;
printf("Enter a value : ");
scanf("%d", &n);

int cntOfZero = 0;
int powersof5 = 5;
while ( n / powersof5 )
{
cntOfZero += n / powersof5;
powersof5 *= 5;
}
printf("Num of zeros : %d\n", cntOfZero);
}

No comments: