用C++写一个编程,编写函数,输入1000以内的所有完数及其因子
时间: 2024-12-17 20:51:02 浏览: 13
当然可以,下面是一个简单的C++程序,它会找出1到1000范围内的完美数(Perfect Number),并列出其所有因子:
```cpp
#include <iostream>
#include <vector>
// 判断一个数是否为完美数
bool isPerfect(int num) {
int sum = 0;
for (int i = 1; i <= num / 2; ++i) {
if (num % i == 0) {
sum += i;
}
}
return sum == num && (num > 1 || sum == 1); // 处理0和1的情况
}
// 找出所有完美数及其因子
void findPerfectNumbersAndFactors(int limit) {
for (int num = 1; num <= limit; ++num) {
if (isPerfect(num)) {
std::cout << "Perfect Number: " << num << "\n";
std::vector<int> factors;
for (int i = 1; i <= num; ++i) {
if (num % i == 0) {
factors.push_back(i);
}
}
std::cout << "Factors: ";
for (const auto &factor : factors) {
std::cout << factor << " ";
}
std::cout << "\n";
}
}
}
int main() {
findPerfectNumbersAndFactors(1000);
return 0;
}
```
当你运行这个程序,它会打印出1000以内所有的完美数及其因子。
阅读全文