Practice › Basics
Trailing Zeros in a Factorial
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Print the number of zeros at the end of n! (n factorial).
Input
A single integer n.
Output
The number of trailing zeros of n!.
Constraints
- 0 ≤ n ≤ 10^18
Each trailing zero comes from a factor 10 = 2 × 5, and there are always more 2s than 5s. Count the 5s: n/5 + n/25 + n/125 + …
Example 1
Input
5
Output
1
Example 2
Input
100
Output
24
Hints
- A trailing zero needs a factor 10 = 2 × 5.
- Factors of 2 are far more common than 5, so count the 5s in 1 × 2 × … × n.
- Multiples of 25 give an extra 5, multiples of 125 another, and so on.
Approach
The number of 5s in n! is ⌊n/5⌋ + ⌊n/25⌋ + ⌊n/125⌋ + … Compute it by repeatedly dividing n by 5 and adding the quotient — this avoids computing 5^k, which could overflow. Never compute n! itself: 25! already has 26 digits.
Complexity: O(log₅ n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
long long zeros = 0;
while (n > 0) {
n /= 5;
zeros += n;
}
cout << zeros << "\n";
return 0;
}Python solution
n = int(input())
zeros = 0
while n > 0:
n //= 5
zeros += n
print(zeros)Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
long zeros = 0;
while (n > 0) {
n /= 5;
zeros += n;
}
System.out.println(zeros);
}
}Solve Trailing Zeros in a Factorial online · All practice problems