非递归方法:
#include <iostream>
#include <vector>
using namespace std;
void primeFactors(int n) {
vector<int> factors;
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
factors.push_back(i);
n /= i;
}
}
for (int i = 0; i < factors.size(); i++) {
cout << factors[i];
if (i != factors.size() - 1) {
cout << " * ";
}
}
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Prime factors of " << n << " are: ";
primeFactors(n);
return 0;
}
递归方法:
#include <iostream>
using namespace std;
void primeFactors(int n, int i) {
if (n <= 1) {
return;
}
while (n % i != 0) {
i++;
}
cout << i;
if (n != i) {
cout << " * ";
}
primeFactors(n / i, i);
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Prime factors of " << n << " are: ";
primeFactors(n, 2);
return 0;
}