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
count
to store the number of trailing zeros. - Iterate from
2
ton
(inclusive). For each iteration:- If
i
is divisible by5
, incrementcount
. This is because every time we encounter a factor of5
, we get a trailing zero. - If
i
is also divisible by25
, incrementcount
again. This is because every time we encounter a factor of25
, we get an additional trailing zero (since there will be more factors of2
to pair with the5
s). - 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;
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.