求正整数n之内的所有完数及其因子的c++代码
时间: 2024-03-14 08:47:58 浏览: 168
用C++语言实现完数求法
以下是求解正整数n以内所有完数及其因子的C++代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
vector<int> getFactors(int num) {
vector<int> factors;
for (int i = 1; i < num; i++) {
if (num % i == 0) {
factors.push_back(i);
}
}
return factors;
}
int main() {
int n;
cout << "请输入正整数n: ";
cin >> n;
for (int i = 1; i <= n; i++) {
int sum = 0;
vector<int> factors = getFactors(i);
for (int j = 0; j < factors.size(); j++) {
sum += factors[j];
}
if (sum == i) {
cout << i << "是一个完数,因子为:";
for (int j = 0; j < factors.size(); j++) {
cout << factors[j] << " ";
}
cout << endl;
}
}
return 0;
}
```
运行程序,输入一个正整数n,即可输出n以内的所有完数及其因子。
阅读全文