AlgoMaster Logo

Factorial Trailing Zeroes

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Count Factors of 5

Intuition:

The basic idea is to count how many times 5 is a factor of numbers from 1 to n. Each multiple of 5 contributes at least one 5 to the factorization. For example, numbers like 25, 125, etc., which throw an additional power of 5, need to be considered as well.

Steps:

  1. Iterate from 5 to n, stepping by 5s.
  2. Count how many times 5 is a factor.
  3. Return the count as the number of trailing zeroes.

Code:

2. Optimized Approach: Mathematical Insight

Intuition:

The count of trailing zeroes is determined by the number of times 5 is a factor in the numbers from 1 to n. The mathematical insight is that we only count multiples of 5, 25, 125, etc., because they contribute one or more extra 5s.

Steps:

  1. Calculate how many multiples of 5, 25, 125, etc., there are in numbers up to n.
  2. This can be done by continuously dividing n by 5, 25, 125... (i.e., continuously dividing by 5) and summing the quotient.
  3. The sum will be our result.

Code: