编程序找出N之内的所有完数,并按下面格式输出其因子 C++输出? its factors are ? ? ?
时间: 2023-09-03 18:12:21 浏览: 145
以下是用 C++ 编写的程序,可以找出 N 以内的所有完数,并按照要求输出:
```cpp
#include <iostream>
#include <vector>
using namespace std;
vector<int> get_factors(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 << "Enter a number N: ";
cin >> n;
for (int i = 1; i <= n; i++) {
vector<int> factors = get_factors(i);
int sum_of_factors = 0;
for (int factor : factors) {
sum_of_factors += factor;
}
if (i == sum_of_factors) {
cout << i << " is a perfect number, its factors are: ";
for (int factor : factors) {
cout << factor << " ";
}
cout << endl;
}
}
return 0;
}
```
运行程序后,输入一个正整数 N,程序会找出 1 到 N 之间的所有完数,并输出其因子,输出格式符合要求。
阅读全文