891233. Factorial Zero Count
Factorial Zero Count
Slug: factorial-zero-count
Difficulty: Easy
Id: 891233
Summary
Given an integer n, find the number of trailing zeros in the factorial of n. For example, for n = 5, the result is 2 because 5! = 120, which has two trailing zeros.
This problem involves basic arithmetic operations and factorial calculations. The key concept is understanding how to calculate the number of trailing zeros in a factorial.
Detailed Explanation
To solve this problem, we need to understand that trailing zeros are formed by pairs of factors of 2 and 5. This means we only need to count the factors of 5 because there will always be more factors of 2 than 5.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
countto store the number of trailing zeros. - Iterate from
2ton(inclusive). For each iteration:- If
iis divisible by5, incrementcount. This is because every time we encounter a factor of5, we get a trailing zero. - If
iis also divisible by25, incrementcountagain. This is because every time we encounter a factor of25, we get an additional trailing zero (since there will be more factors of2to pair with the5s). - Continue this process until
i > n.
- If
- Return the value of
count.
The time complexity for this solution is O(n), as we need to iterate from 2 to n. The space complexity is O(1), as we only use a constant amount of space.
Optimized Solutions
Java
public int factorialZeroCount(int n) {
int count = 0;
for (int i = 5; i <= n; i += 5) {
while (i % 25 == 0) {
count++;
i /= 25;
}
while (i % 5 == 0) {
count++;
i /= 5;
}
}
return count;
}