#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

bool isPrime(int num) {
    if (num <= 1) {
        return false;
    }
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

vector<int> findFlawlessPrimes(string numStr) {
    vector<int> flawlessPrimes;
    
    for (int i = 0; i < numStr.size() - 1; i++) {
        for (int j = i + 1; j < numStr.size(); j++) {
            string tempStr = numStr;
            swap(tempStr[i], tempStr[j]);
            int num = stoi(tempStr);
            if (isPrime(num)) {
                flawlessPrimes.push_back(num);
            }
        }
    }
    
    sort(flawlessPrimes.begin(), flawlessPrimes.end());
    return flawlessPrimes;
}

int main() {
    string numStr;
    cin >> numStr;
    
    vector<int> result = findFlawlessPrimes(numStr);
    
    for (int i = 0; i < result.size(); i++) {
        cout << result[i];
        if (i != result.size() - 1) {
            cout << ',';
        }
    }
    
    return 0;
}

算法思路:

  1. 判断素数: 使用 isPrime() 函数判断一个整数是否为素数。
  2. 交换数字: 遍历数字字符串,交换其中两位数字,生成新的数字。
  3. 查找无暇素数: 判断生成的数字是否为素数,如果是,则将其加入 flawlessPrimes 列表。
  4. 排序输出:flawlessPrimes 列表进行排序,并输出所有无暇素数。

代码解释:

  • isPrime(int num) 函数:
    • 使用循环判断 num 是否能被 2 到 sqrt(num) 之间的任何整数整除。
    • 如果能整除,则 num 不是素数,返回 false;否则,num 是素数,返回 true
  • findFlawlessPrimes(string numStr) 函数:
    • 遍历数字字符串 numStr,交换其中两位数字,生成新的数字 num
    • 使用 isPrime(num) 函数判断 num 是否为素数。
    • 如果 num 是素数,则将其加入 flawlessPrimes 列表。
    • flawlessPrimes 列表进行排序,返回结果。
  • main() 函数:
    • 获取输入的数字字符串 numStr
    • 调用 findFlawlessPrimes(numStr) 函数查找所有无暇素数。
    • 输出所有无暇素数,以逗号隔开。

示例:

输入:

321314%

输出:

13,31

代码说明:

代码使用 C++ 语言编写,包含头文件 <iostream><string><vector><algorithm>。使用 cin 获取输入,使用 cout 输出结果。代码逻辑清晰,易于理解和修改。

总结:

本文介绍了如何使用 C++ 语言实现无暇素数查找算法,并提供了完整代码和示例。该代码可以帮助读者了解算法实现细节,并可以作为学习 C++ 编程的参考。

C++ 实现 无暇素数 查找算法

原文地址: https://www.cveoy.top/t/topic/jgjH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录