Factorial Trailing Zeroes
Problem Statement
Given an integer n, return the number of trailing zeroes in n!.
Examples
Example 1:
Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: n = 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Example 3:
Input: n = 0
Output: 0
Constraints
Solution
Approach
To find the number of trailing zeroes in n!, we need to count the number of times 10 is a factor in the numbers from 1 to n. Since 10 is the product of 2 and 5, and there are usually more factors of 2 than 5, the number of trailing zeroes is determined by the number of times 5 is a factor in the numbers from 1 to n.
Algorithm
- Initialize
countto 0. This will hold the number of trailing zeroes. - While
nis greater than 0:
- Divide
nby 5. - Add the result to
count. - Repeat the process with the updated value of
n.
- Return the final
count.
Implementation
public class Solution {
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}
}
Complexity Analysis
-
Time complexity:
- The time complexity is because we repeatedly divide
nby 5.
- The time complexity is because we repeatedly divide
-
Space complexity:
- The space complexity is as we are using only a constant amount of extra space
Conclusion
This solution efficiently calculates the number of trailing zeroes in n! by counting the factors of 5 in the numbers from 1 to n. The approach is both time and space efficient, making it suitable for handling large input sizes.