Opening the reading…
Opening the reading…
DSA FUNDAMENTALS › MATH BASICS
A trailing zero appears when the value ends with a factor of 10. Since 10 = 2 * 5, each trailing zero uses one factor of 2 and one factor of 5. The question for 25! is therefore: how many complete pairs of 2 and 5 can its multiplication contain?
The factors of 2 appear more often than the factors of 5 in 25!. Every even number contributes at least one factor of 2, while only 5, 10, 15, 20, and 25 contribute a factor of 5. Because there are more factors of 2 available, the factors of 5 run out first. Counting the factors of 5 therefore tells you exactly how many pairs, and hence how many trailing zeroes, can be formed.
10 = 2 * 5
one factor of 2 + one factor of 5 = one trailing zeroWhich factor limits the number of trailing zeroes in 25!?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The multiples of 5 from 1 through 25 each provide a first factor of 5. The numbers 5, 10, 15, and 20 each contribute one, and 25 contributes one as well. That first pass gives 5 factors of 5, which is the value floor(25 / 5) finds.
But 25 is not just one factor of 5. It is 5 * 5, so it contributes a second factor of 5 after its first one has been counted. The total is therefore 5 + 1 = 6 factors of 5. Returning floor(25 / 5) alone gives 5 and misses the extra factor hidden inside 25.
Integer division by 5 counts the numbers that supply a first factor of 5. For n = 25, 25 / 5 = 5, so there are five first-layer factors. Dividing that quotient again counts numbers that supply a second factor of 5: 5 / 5 = 1. The next quotient is 1 / 5 = 0, so no further layer exists.
int n = 25;
int zeroes = 0;
while (n > 0) {
n /= 5;
zeroes += n;
}
// zeroes is 6The working value moves through 25, 5, 1, and 0. The loop adds 5 on the first pass and 1 on the second, giving 6. The value 25 counts the first factor layer, and the value 5 counts the extra factor inside 25. Stopping when the working value becomes 0 ensures that every factor layer is counted once.
For n = 25, enter the two quotients added and their final sum.
n = 25
n /= 5
zeroes += n
n /= 5
zeroes += nCheckpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
You do not need to calculate and store the full value of 25! to find its trailing zeroes. The repeated-division loop stores only the working value and the count. For n = 25, it handles the small trace 25, 5, 1, 0 instead of building a much larger factorial value.
The loop uses constant extra space, O(1), because it keeps only a fixed number of variables. Each pass divides the working value by 5, so the number of passes is O(log base 5 of n). This avoids overflow from constructing the factorial, and it still counts every factor-of-5 layer that can create a trailing zero.