LeetCode 172: Factorial Trailing Zeroes

Math

Problem Description

Explanation

To count the number of trailing zeroes in the factorial of a number, we need to count the number of factors of 5 in the factorial. This is because the number of 5s in the prime factorization of a number will determine the number of trailing zeroes in its factorial. We can iteratively divide the number by 5 and sum up the quotients to get the total number of trailing zeroes.

Algorithm

  1. Initialize a variable count to 0.
  2. Iterate over the numbers from 5 to n in steps of 5.
  3. For each number, divide it by 5 and add the quotient to count.
  4. Return count as the number of trailing zeroes in n!.

Time Complexity

The time complexity of this algorithm is O(log n) since we are dividing the number by 5 in each iteration.

Space Complexity

The space complexity of this algorithm is O(1) as we are using only a constant amount of extra space.

Solutions

class Solution {
    public int trailingZeroes(int n) {
        int count = 0;
        for (int i = 5; i <= n; i += 5) {
            int num = i;
            while (num % 5 == 0) {
                count++;
                num /= 5;
            }
        }
        return count;
    }
}

Loading editor...