And the fate of this topic: I interviewed a big factory in 18 years of the pen test
We started looking for interesting patterns. If some number in the factorial is a multiple of 5, we can generate a 0 with 2, and the number of multiples of 2 — even numbers — is obviously more than the number of multiples of 5
5! -> 5 * 2 -> 1 zero 10! -> 10 * (5 * 2) -> 2 zeros 15! -> (15 * 2) * 10 * (5 * 2) -> 3 zeros 20! -> 20 * (15 * 2) * 10 * (5 * 2) -> 4 zeros 25! - > (25 * 2) * * 20 (15 * 2) * 10 * (5 * 2) - > 5 zero 30! - > 30 * 20 (25 * 2) * * (15 * 2) * (10) * (5 * 2) - > 6 zero 35! - > (35 * 2) * 30 * 20 (25 * 2) * * (15 * 2) * (10) * (5 * 2) - > 7 zero 40! - > 40 * (35 * 2) * 30 * 20 (25 * 2) * * (15 * 2) * (10) * (5 * 2) - > 8 zero 45! - > (45 * 2) * 40 * (35 * 2) * 30 * 20 (25 * 2) * * (15 * 2) * (10) * (5 * 2) - > 9 zero 50! - > 50 * (45 * 2) * 40 * (35 * 2) * 30 * 20 (25 * 2) * * (15 * 2) * (10) * (5 * 2) - > 10 zeroCopy the code
Wouldn’t that be n divided by 5 and then rounded down
Consider that 25 can be divided into 5 * 5, which can produce 2 zeros, 125 can be divided into 5 * 5 * 5, which can produce 3 zeros…
5! -> 5 * 2 -> 5 to the first power produces a zero 10! -> 10 * (5 * 2) -> 5 to the first power produces two zeros 15! -> (15 * 2) * 10 * (5 * 2) -> 5 to the first power to generate three zeros 20! -> 20 * (15 * 2) * 10 * (5 * 2) -> 5 to the first power to generate four zeros 25! -> (5 * 5 * 2 * 2) * 20 * (15 * 2) * 10 * (5 * 2) -> 5 to the 1 to generate 5 zeros + 5 to the 2 to generate 1 zeros 30! -> 30 * (5 * 5 * 2 * 2) * 20 * (15 * 2) * (10) * (5 * 2) -> 6 zeros generated by 5 to the 1 + 1 zeros generated by 5 to the 2 35! -> (35 * 2) * 30 * (5 * 5 * 2 * 2) * 20 * (15 * 2) * (10) * (5 * 2) -> 5 to the 1 generated 7 zeros + 5 to the 2 generated 1 zeros 40! -> 40 * (35 * 2) * 30 * (5 * 5 * 2 * 2) * 20 * (15 * 2) * (10) * (5 * 2) -> 5 to the 1 generated 8 zeros + 5 to the 2 generated 1 zeros 45! -> (45 * 2) * 40 * (35 * 2) * 30 * (5 * 5 * 2 * 2) * 20 * (15 * 2) * (10) * (5 * 2) -> 9 zeros generated by the first power of 5 + 1 zeros generated by the second power of 5 50! - > (5 * 5 * 2 * 2) * (45 * 2) * 40 * (35 * 2) * 30 * (5 * 5 * 2 * 2) * * 20 (15 * 2) * * (5 * 2) (10) - > 5 + 1 power generated 10 zero Five to the second power generates two zerosCopy the code
If we look at the pattern again, we can see that this is the sum of n over 5 integers taken down
const res = Math.floor(n / 5) + Math.floor(n / (5 * 5)) + ...
Copy the code
var trailingZeroes = function (n) {
let init = 5
let res = 0
while (init <= n) {
res += Math.floor(n / init)
init *= 5
}
return res
}
Copy the code