Your task is to calculate the number of trailing zeros in the factorial of a given number.
Example:
Input: n = 20
Output: 4
Approach
Java
public class TrailingZeros {public static void main(String[] args) {long n = 20;System.out.println(trailingZeros(n));}static long trailingZeros(long n) {long cnt = 0;while (n > 0) {cnt += n / 5;n = n / 5;}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;long long trailingZeros(long long n){long long cnt = 0;while (n){cnt += n / 5;n = n / 5;}return cnt;}int main(){long long n = 20;cout<<trailingZeros(n);return 0;}
No comments:
Post a Comment