在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的質因數分解結果。