Number of trailing zeros in N * (N – 2) * (N – 4)*….
Last Updated :
20 Feb, 2022
Given an integer N, the task is to find the number of trailing zeros in the decimal notation of f(N) where f(N) = 1 if N < 2 and f(N) = N * f(N – 2) if N ? 2
Examples:
Input: N = 12
Output: 1
f(12) = 12 * 10 * 8 * 6 * 4 * 2 = 46080
Input: N = 7
Output: 0
Approach: The number of trailing zeros when f(N) is expressed in decimal notation is the number of times f(N) is divisible by 2 and the number of times f(N) is divisible by 5. There are two cases:
- When N is odd then f(N) is the product of some odd numbers, so it does not break at 2. So the answer is always 0.
- When N is even then f(N) can be represented as 2 (1 * 2 * 3 * …. * N/2). The number of times f(N) is divisible by 2 is greater than the number of times divisible by 5, so only consider the number of times divisible by 5. Now, this problem is similar to count trailing zeroes in factorial of a number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findTrailingZeros( int n)
{
if (n & 1)
return 0;
else {
int ans = 0;
n /= 2;
while (n) {
ans += n / 5;
n /= 5;
}
return ans;
}
}
int main()
{
int n = 12;
cout << findTrailingZeros(n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int findTrailingZeros( int n)
{
if ((n & 1 ) == 1 )
return 0 ;
else
{
int ans = 0 ;
n /= 2 ;
while (n != 0 )
{
ans += n / 5 ;
n /= 5 ;
}
return ans;
}
}
public static void main (String[] args)
{
int n = 12 ;
System.out.println(findTrailingZeros(n));
}
}
|
Python3
def findTrailingZeros(n):
if (n & 1 ):
return 0
else :
ans = 0
n / / = 2
while (n):
ans + = n / / 5
n / / = 5
return ans
n = 12
print (findTrailingZeros(n))
|
C#
using System;
class GFG
{
static int findTrailingZeros( int n)
{
if ((n & 1) == 1)
return 0;
else
{
int ans = 0;
n /= 2;
while (n != 0)
{
ans += n / 5;
n /= 5;
}
return ans;
}
}
public static void Main(String[] args)
{
int n = 12;
Console.WriteLine(findTrailingZeros(n));
}
}
|
Javascript
<script>
function findTrailingZeros(n)
{
if (n & 1)
return 0;
else
{
let ans = 0;
n = parseInt(n / 2);
while (n)
{
ans += parseInt(n / 5);
n = parseInt(n / 5);
}
return ans;
}
}
let n = 12;
document.write(findTrailingZeros(n));
</script>
|
Time Complexity: O(log5n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...