写一个C++程序,求1000之内所有完数
时间: 2024-05-26 14:12:43 浏览: 17
好的,以下是一个求1000以内所有完数的C++程序:
#include <iostream>
using namespace std;
int main()
{
int i, j, sum;
for (i = 1; i <= 1000; i++)
{
sum = 0;
for (j = 1; j < i; j++)
{
if (i % j == 0)
{
sum += j;
}
}
if (sum == i)
{
cout << i << " ";
}
}
return 0;
}
希望对你有帮助,还有什么我可以为您效劳的吗?
相关问题
C++编写求100之内的所有完数
好的,下面是 C++ 代码实现:
```cpp
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 100; i++) {
int sum = 0;
for (int j = 1; j <= i / 2; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
cout << i << " ";
}
}
cout << endl;
return 0;
}
```
程序的思路是,对于每个数字 i,从 1 遍历到 i 的一半,如果 i 能够被这个数整除,就将这个数加入到 sum 中。最后检查 sum 是否等于 i,如果相等就输出 i,表示 i 是一个完数。
运行程序后,输出结果如下:
```
6 28
```
求正整数n之内的所有完数及其因子的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以内的所有完数及其因子。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)