Counting trailing zeros of factorial numbers in any number system
How can I calculate the number of trailing zeros of the factorial of a number in a certain number system?
Let's look at the case when we are in the 10th number system, and then see how we can generalize this into a universal solution. We are given the number N and for its factorial we need to find the number of trailing zeros. The solution will be quite simple - the sum:
Math.floor(N/5) + Math.floor(N/25) + Math.floor(N/125) + Math.floor(N/625) + ...
We can generalize it into such a formula:
Why in the example above we divide by 5? Because 10 can be obtained by multiplying 5 by 2. Therefore, the complete solution will have two formulas:
Solution to our problem
To calculate the final zeros of the factorial of a number in a specific number system, I compiled the algorithm below:
- Factor the number B of the number system.
- Divide the number N by each unique prime factor K, multiplying K by itself until
will be more than one, while rounding each result to a smaller integer.
- If, when expanding the number of the number system, we get several identical prime factors K, then we should divide the result above by the number of identical K.
- Of all the divisions of N by each unique factor K, choose the smallest quotient, which will be our answer.
I will show it with an example.
Let the number N = 5, the number system B = 12. Factorial 5! = 120, and 120 in the 12th system is A0. We see that in a finite number system the factorial of the original number has one zero. If we decompose 12 into prime factors, we get 2, 2, 3. We have two unique numbers: 2 and 3. Following our algorithm, we will fulfill point 2 with the number 2.
We do the same with 3:
Consider another example.
Let the number N = 16, the number system B = 16. The factorial 16! = 20922789888000, and 20922789888000 in the 16th system - 130777758000. We see that in the final number system the factorial of the original number has three zeros. If we decompose 16 into prime factors, we get 2, 2, 2, 2. Here we have only one unique number, therefore, item 2 is executed only once:
PS Most of the material for the post translated from here . Posted by Aditya Ramesh .