给定一个整数Y,找到最小的X使得X!至少包含Y个尾随零。
先决条件–计算数字阶乘中的尾随零
例子:
Input : Y = 2
Output : 10
10! = 3628800, which has 2 trailing zeros. 9! = 362880, which has 1 trailing zero. Hence, 10 is the correct answer.
Input : Y = 6
Output : 25
25! = 15511210043330985984000000, which has 6 trailing zeros. 24! = 620448401733239439360000, which has 4 trailing zeros. Hence, 25 is the correct answer.
方法:使用Binary Search可以轻松解决问题。 N中的尾随零数!由N!中的因子5的计数给出。请阅读本文以了解先决条件。 countFactor(5,N)函数以N为单位返回因子5的计数!等于N!中尾随零的计数。 X的最小数就是X!通过使用此函数在范围[0,5 * Y]上进行二进制搜索,可以快速计算出至少包含Y个结尾的零。
下面是上述方法的实现。
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to count the number
// of factors P in X!
int countFactor(int P, int X)
{
if (X < P)
return 0;
return (X / P + countFactor(P, X / P));
}
// Function to find the smallest X such
// that X! contains Y trailing zeros
int findSmallestX(int Y)
{
int low = 0, high = 5 * Y;
int N = 0;
while (low <= high) {
int mid = (high + low) / 2;
if (countFactor(5, mid) < Y) {
low = mid + 1;
}
else {
N = mid;
high = mid - 1;
}
}
return N;
}
// Driver code
int main()
{
int Y = 10;
cout << findSmallestX(Y);
return 0;
}
Java
// Java implementation of the above approach
class GFG
{
// Function to count the number
// of factors P in X!
static int countFactor(int P, int X)
{
if (X < P)
return 0;
return (X / P + countFactor(P, X / P));
}
// Function to find the smallest X such
// that X! contains Y trailing zeros
static int findSmallestX(int Y)
{
int low = 0, high = 5 * Y;
int N = 0;
while (low <= high)
{
int mid = (high + low) / 2;
if (countFactor(5, mid) < Y)
{
low = mid + 1;
}
else
{
N = mid;
high = mid - 1;
}
}
return N;
}
// Driver code
public static void main(String args[])
{
int Y = 10;
System.out.println(findSmallestX(Y));
}
}
// This code is contributed by Ryuga
Python3
# Python3 implementation of the approach
# Function to count the number
# of factors P in X!
def countFactor(P, X):
if (X < P):
return 0;
return (X // P + countFactor(P, X // P));
# Function to find the smallest X such
# that X! contains Y trailing zeros
def findSmallestX(Y):
low = 0;
high = 5 * Y;
N = 0;
while (low <= high):
mid = (high + low) // 2;
if (countFactor(5, mid) < Y):
low = mid + 1;
else:
N = mid;
high = mid - 1;
return N;
# Driver code
Y = 10;
print(findSmallestX(Y));
# This code is contributed by mits
C#
// C# implementation of the approach
class GFG
{
// Function to count the number
// of factors P in X!
static int countFactor(int P, int X)
{
if (X < P)
return 0;
return (X / P + countFactor(P, X / P));
}
// Function to find the smallest X such
// that X! contains Y trailing zeros
static int findSmallestX(int Y)
{
int low = 0, high = 5 * Y;
int N = 0;
while (low <= high)
{
int mid = (high + low) / 2;
if (countFactor(5, mid) < Y)
{
low = mid + 1;
}
else
{
N = mid;
high = mid - 1;
}
}
return N;
}
// Driver code
static void Main()
{
int Y = 10;
System.Console.WriteLine(findSmallestX(Y));
}
}
// This code is contributed by mits
PHP
输出:
45