用 C++ 求出含有素数位数字的最大数
本教程中,我们将编写一个程序,该程序找出小于 n 的具有素数位数的最大数。
我们来看一下解决此问题所需的步骤。
- 编写从 0 到 n 迭代的循环。
- 如果当前数字不是素数。
- 在数字小于 2 时,将 i 值减 1。如果 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
结论
如果您对本教程有任何疑问,请在评论部分说明。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP