#include <iostream>
#include <vector>
using namespace std;
void primeFactors(int n) {
vector<int> factors;
while (n % 2 == 0) {
factors.push_back(2);
n = n / 2;
}
for (int i = 3; i*i <= n; i = i + 2) {
while (n % i == 0) {
factors.push_back(i);
n = n / i;
}
}
if (n > 2) {
factors.push_back(n);
}
cout << "Prime factors of the number are: ";
for (int i = 0; i < factors.size(); i++) {
cout << factors[i] << " ";
}
}
int main() {
int n;
cout << "Enter a number to find its prime factors: ";
cin >> n;
primeFactors(n);
return 0;
}
這是一個用于分解質因數的高效算法,首先判斷2是否為n的因數,然后從3開始每次遞增2判斷是否為質因數,直到質因數的平方大于n為止。最后判斷n是否大于2,如果是則加入質因數列表中。輸出結果為輸入的數的所有質因數。