Trailing Zeroes in Factorial
Medium math
Description
Constraints
0 <= n <= 10^9
Examples
Input: n = 25
Output: 6
Hints (1)
- Count factors of 5, then 25, then 125 and so on.
Solutions
Count factors of five. · Time O(log n) · Space O(1)
func trailingZeroes(n int) int {
count := 0
for n >= 5 {
n /= 5
count += n
}
return count
}
Count factors of five. · Time O(log n) · Space O(1)
function trailingZeroes(n) {
let count = 0;
while (n >= 5) { n = Math.floor(n / 5); count += n; }
return count;
}
Count factors of five. · Time O(log n) · Space O(1)
function trailingZeroes($n) {
$count = 0;
while ($n >= 5) { $n = intdiv($n, 5); $count += $n; }
return $count;
}
Count factors of five. · Time O(log n) · Space O(1)
def trailingZeroes(n):
count = 0
while n >= 5:
n //= 5
count += n
return count
Count factors of five. · Time O(log n) · Space O(1)
function trailingZeroes(n: number): number {
let count = 0;
while (n >= 5) { n = Math.floor(n / 5); count += n; }
return count;
}
Create a free account to submit solutions, track progress and save problems.
Create account