在 C++ 中找到最小的数 X,使得 X!包含至少 Y 个尾随零
我们必须取一个数 Y,我们将找到最小的数 X,使得 X!包含至少 Y 个尾随零。例如,如果 Y = 2,则 X = 10。因为 X! = 3228800。它有 Y 个零。
我们可以使用二分查找来解决这个问题。N! 中尾随零的个数由 N! 中因子 5 的个数给出。可以在范围 [0, 5*Y] 中使用二分查找找到 X
示例
#include<iostream>
using namespace std;
int factorCount(int n, int X) {
if (X < n)
return 0;
return (X / n + factorCount(n, X / n));
}
int findX(int Y) {
int left = 0, right = 5 * Y;
int N = 0;
while (left <= right) {
int mid = (right + left) / 2;
if (factorCount(5, mid) < Y) {
left = mid + 1;
}else {
N = mid;
right = mid - 1;
}
}
return N;
}
int main() {
int Y = 4;
cout << "Smallest value of X: " << findX(Y);
}输出
Smallest value of X: 20
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP