题目描述:
请用C++写一个RSA加密算法,任意输入10位以及10位以内正整数num,请对其进行因数分解,找到事哪两个素数的乘积。例如输入的正整数是15,输出数字从小到大排序并用空格分隔,如输出是3 5;如果分解失败,则输出-1 -1
示例1:
输入:
15
输出
3 5
示例2:
输入
27
输出
-1 -1
C++源码:
#include <iostream>
#include <string>
#include <ctime>
#include <vector>
#include <algorithm>
using namespace std;
// 判断素数的函数
bool isPrime(int num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 == 0 || num % 3 == 0) return false;
for (int i = 5; i * i <= num; i += 6)
if (num % i == 0 || num % (i + 2) == 0) return false;
return true;
}
// 简单因数分解,针对10位以内的正整数
vector<int> factorize(int num) {
vector<int> factors;
for (int i = 2; i <= static_cast<int>(sqrt(num)); ++i) {
while (num % i == 0) {
if (isPrime(i)) {
factors.push_back(i);
}
num /= i;
}
}
if (num > 1 && isPrime(num)) {
factors.push_back(num);
}
return factors.size() == 2 ? factors : vector<int>{ -1, -1 };
}
int main() {
int num;
cout << "请输入一个[1,2147483647]位及以内的正整数: ";
cin >> num;
if (num <= 0 || num > 2147483647) {
cout << "输入的数字不在10位及以内的范围内。\n";
return 1;
}
vector<int> factors = factorize(num);
if (factors[0] != -1) {
sort(factors.begin(), factors.end());
cout << factors[0] << " " << factors[1] << endl;
}
else {
cout << "-1 -1" << endl;
}
system("pause");
return 0;
}