给定整数N ,任务是找到f(N)的十进制表示形式的尾随零个数,如果N <2 ,则f(N)= 1,如果f(N)= N * f(N – 2),则f(N)= 1 N≥2
例子:
Input: N = 12
Output: 1
f(12) = 12 * 10 * 8 * 6 * 4 * 2 = 46080
Input: N = 7
Output: 0
方法:用十进制表示法表示f(N)时的尾随零数是f(N)被2整除的次数和f(N)被5可整除的次数。有两种情况:
- 当N是奇数时,则f(N)是一些奇数的乘积,因此它不会在2处中断。因此,答案始终为0 。
- 当N为偶数时, f(N)可以表示为2(1 * 2 * 3 *…。* N / 2) 。 f(N)可被2整除的次数大于可被5整除的次数,因此仅考虑可被5整除的次数。现在,此问题类似于在数字阶乘中计数尾随零。
下面是上述方法的实现:
CPP
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count of
// trailing 0s in the given function
int findTrailingZeros(int n)
{
// If n is odd
if (n & 1)
return 0;
// If n is even
else {
int ans = 0;
// Find the trailing zeros
// in n/2 factorial
n /= 2;
while (n) {
ans += n / 5;
n /= 5;
}
// Return the required answer
return ans;
}
}
// Driver code
int main()
{
int n = 12;
cout << findTrailingZeros(n);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to return the count of
// trailing 0s in the given function
static int findTrailingZeros(int n)
{
// If n is odd
if ((n & 1) == 1)
return 0;
// If n is even
else
{
int ans = 0;
// Find the trailing zeros
// in n/2 factorial
n /= 2;
while (n != 0)
{
ans += n / 5;
n /= 5;
}
// Return the required answer
return ans;
}
}
// Driver code
public static void main (String[] args)
{
int n = 12;
System.out.println(findTrailingZeros(n));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to return the count of
# trailing 0s in the given function
def findTrailingZeros(n):
# If n is odd
if (n & 1):
return 0
# If n is even
else:
ans = 0
# Find the trailing zeros
# in n/2 factorial
n //= 2
while (n):
ans += n // 5
n //= 5
# Return the required answer
return ans
# Driver code
n = 12
print(findTrailingZeros(n))
# This code is contributed by mohit kumar 29
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the count of
// trailing 0s in the given function
static int findTrailingZeros(int n)
{
// If n is odd
if ((n & 1) == 1)
return 0;
// If n is even
else
{
int ans = 0;
// Find the trailing zeros
// in n/2 factorial
n /= 2;
while (n != 0)
{
ans += n / 5;
n /= 5;
}
// Return the required answer
return ans;
}
}
// Driver code
public static void Main(String[] args)
{
int n = 12;
Console.WriteLine(findTrailingZeros(n));
}
}
// This code is contributed by 29AjayKumar
输出:
1