Finding trailing zeros of a factorial JavaScript

Given an integer n, we have to write a function that returns the number of trailing zeroes in n! (factorial).

For example:

trailingZeroes(4) = 0
trailingZeroes(5) = 1
because 5! = 120
trailingZeroes(6) = 1

How It Works

Trailing zeros are created by multiplying factors of 10, which come from pairs of 2 and 5. Since there are always more factors of 2 than 5 in any factorial, we only need to count factors of 5. We count multiples of 5, then 25 (5²), then 125 (5³), and so on.

Example

const num = 17;
const findTrailingZeroes = num => {
    let cur = 5, total = 0;
    while (cur <= num) {
        total += Math.floor(num / cur);
        cur *= 5;
    }
    return total;
};
console.log(findTrailingZeroes(num));
console.log(findTrailingZeroes(5));
console.log(findTrailingZeroes(1));

Output

3
1
0

Step-by-Step Breakdown

Let's trace through findTrailingZeroes(17):

const traceTrailingZeroes = num => {
    let cur = 5, total = 0;
    console.log(`Finding trailing zeros for ${num}!`);
    
    while (cur <= num) {
        let count = Math.floor(num / cur);
        total += count;
        console.log(`Multiples of ${cur}: ${count}, running total: ${total}`);
        cur *= 5;
    }
    return total;
};

traceTrailingZeroes(17);
Finding trailing zeros for 17!
Multiples of 5: 3, running total: 3
Multiples of 25: 0, running total: 3

More Examples

console.log(`25! has ${findTrailingZeroes(25)} trailing zeros`);
console.log(`100! has ${findTrailingZeroes(100)} trailing zeros`);
console.log(`0! has ${findTrailingZeroes(0)} trailing zeros`);
25! has 6 trailing zeros
100! has 24 trailing zeros
0! has 0 trailing zeros

Conclusion

To find trailing zeros in n!, count factors of 5 by dividing n by powers of 5 and summing the results. This efficient algorithm runs in O(log n) time complexity.

Updated on: 2026-03-15T23:19:00+05:30

471 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements