Tuesday, January 12, 2010

Factorial and their trailing zeroes

In SPOJ, there is a problem to find the number of trailing zeroes in the factorial of a number. Though the question seems intimidating, the solution is rather simple.

zeroes come from multiplying the number by 10. To find the number of times the factorial has been multiplied by 10, we can find the number of times 10 is a factor in the factorial expansion of the number. 5 x 2 = 10 is also possible. So instead of finding the factors of 10, we can find it for 5. All the powers of 5 like, 25,125,etc should also be considered to add number of 5 factors to the expansion.

Thus, to find number of trailing zeroes, keep adding the floor of (num/power of 5) until the division is less than 1. The reason why we ignore the reminders in the factors are we need only whole factors not partial ones.

For more detailed explanation see the Source

No comments: