Trailing Zeroes in Factorial of a Number – FCTRL – SPOJ
Now we can approach it in 2 ways –
the first approach is to calculate factorial of a number and then calculate the number of trailing zeros from the result. But for any value greater than 12 we will see integer exceed.
So let’s go with the second approach and Find a relation between number and trailing zeros and n. The number of zeros will be directly related to the number of 10’s available in result and 10 will be the result of 5*2. The number of 2’s in the pair can be taken from any even number. So the problem is now reduced to getting the count of 5’s in factorial or Count of 5s in prime factors of n!
find no of 5’s –
- Take the number that you’ve been given the factorial of.
- Divide by 5; if you get a decimal, truncate to a whole number.
- Divide by 52 = 25; if you get a decimal, truncate to a whole number.
- Divide by 53 = 125; if you get a decimal, truncate to a whole number.
- Continue with ever-higher powers of 5, until your division results in a number less than 1. Once the division is less than 1, stop.
- Sum all the whole numbers you got in your divisions. This is the number of trailing zeroes
Trailing 0s or 5s in n! = Count of 5s in prime factors of n! = floor(n/5) + floor(n/25) + floor(n/125) + floor(n/625) + ....
Practice Problem – http://www.spoj.com/problems/FCTRL/
Other Resources –