分解质因子c++代码
时间: 2024-01-21 13:14:36 浏览: 87
以下是一个用C++编写的分解质因数的代码示例:
```cpp
#include <iostream>
#include <vector>
using namespace std;
vector<int> primeFactors(int n) {
vector<int> factors;
while (n % 2 == 0) {
factors.push_back(2);
n = n / 2;
}
for (int i = 3; i <= sqrt(n); i = i + 2) {
while (n % i == 0) {
factors.push_back(i);
n = n / i;
}
}
if (n > 2) {
factors.push_back(n);
}
return factors;
}
int main() {
int num;
cout << "请输入一个正整数:";
cin >> num;
vector<int> factors = primeFactors(num);
cout << num << "的质因子为:";
for (int i = 0; i < factors.size(); i++) {
cout << factors[i] << " ";
}
return 0;
}
```
阅读全文