[front end algorithm] zero after factorization, twice traversal

Time:2021-6-6

Given an integer n, return n! The number of zeros in the result mantissa.

Example 1:
Input: 3
Output: 0
Explanation: 3= 6, there is no zero in the mantissa.
Example 2:
Input: 5
Output: 1
Explanation: 5= 120, one zero in the mantissa
  • Note: the time complexity of your algorithm should be o (log n).

Solution code:

/**
 * @param {number} n
 * @return {number}
 */
var trailingZeroes = function(n) {
    let result = 1;
    let i = 1;
    while (i <= 5) {
        result *= i;
        i++;
    };
    var num = 0;
    while (n > 0) {
        n = (n - (n % 5)) / 5;
        num += n;
    }
    return num
};

Knowledge points

  • Find the zero after the factorial number

The number of zeros at the end depends on the number of factors 2 and 5 in the multiplication. Obviously, the number of factors 2 in multiplication is greater than that of 5, so we only need to count the number of factors 5.

Such as 5!
Please 5! 5/5 = 1;// 120 followed by a zero
The number of multiples of 5 is 1024 / 5 = 204
The number of multiples of 25 is 1024 / 25 = 40
The number of multiples of 125 is: 1024 / 125 = 8
The number of multiples of 625 is 1024 / 625 = 1
So 1024! There are 204 + 40 + 8 + 1 = 253 factor 5.
That is to say, 1024! There are 253 zeros at the end.