在C++中,可以使用一种空间优化的技巧来分解质因数,即只存储需要的数据,而不是存储所有可能的数据。具体步骤如下:
以下是一个示例代码:
#include <iostream>
#include <vector>
using namespace std;
vector<int> primeFactors(int num) {
vector<int> factors;
while (num % 2 == 0) {
factors.push_back(2);
num = num / 2;
}
for (int i = 3; i * i <= num; i = i + 2) {
while (num % i == 0) {
factors.push_back(i);
num = num / i;
}
}
if (num > 1) {
factors.push_back(num);
}
return factors;
}
int main() {
int num = 56;
vector<int> factors = primeFactors(num);
cout << "Prime factors of " << num << " are: ";
for (int factor : factors) {
cout << factor << " ";
}
return 0;
}
以上代码实现了一个空间优化的质因数分解函数,并输出了56的质因数分解结果。