在本教程中,我们将编写一个程序,该程序查找带有小于n的质数的最大数字。
让我们看看解决问题的步骤。
编写一个从0迭代到n的循环。
当数字小于2时,请减小i值。如果i值为负,则将其设为0。
用下一个最小的质数位更新当前索引值。
从下一个索引开始,将每个数字都设为7。
如果当前数字不是素数。
返回n。
让我们看一下代码。
#include <bits/stdc++.h>
using namespace std;
bool isPrime(char c) {
return c == '2' || c == '3' || c == '5' || c == '7';
}
void decrease(string& n, int i) {
if (n[i] <= '2') {
n.erase(i, 1);
n[i] = '7';
}else if (n[i] == '3') {
n[i] = '2';
}else if (n[i] <= '5') {
n[i] = '3';
}else if (n[i] <= '7') {
n[i] = '5';
}else {
n[i] = '7';
}
return;
}
string getPrimeDigitsNumber(string n) {
for (int i = 0; i < n.length(); i++) {
if (!isPrime(n[i])) {
while (n[i] <= '2' && i >= 0) {
i--;
}
if (i < 0) {
i = 0;
}
decrease(n, i);
for (int j = i + 1; j < n.length(); j++) {
n[j] = '7';
}
break;
}
}
return n;
}
int main() {
string n = "7464";
cout << getPrimeDigitsNumber(n) << endl;
return 0;
}输出结果
如果运行上面的代码,则将得到以下结果。
7377