C加加编程找出n以内的所有完数
时间: 2024-06-13 16:06:58 浏览: 19
以下是C++编程找出n以内的所有完数的代码:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int sum = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
cout << i << " its factors are ";
for (int j = 1; j < i; j++) {
if (i % j == 0) {
cout << j << " ";
}
}
cout << endl;
}
}
return 0;
}
```
相关问题
c加加求1000以内的完数代码
以下是C++代码:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 1000; i++) {
int sum = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
cout << i << "是完数" << endl;
}
}
return 0;
}
用c加加写找出m到n之间的素数
以下是用 C++ 写的找出 m 到 n 之间的素数的代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
bool is_prime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int m, n;
cout << "请输入 m 和 n:" << endl;
cin >> m >> n;
cout << "m 到 n 之间的素数有:" << endl;
for (int i = m; i <= n; i++) {
if (is_prime(i)) {
cout << i << " ";
}
}
cout << endl;
return 0;
}
```
如果您需要使用 C 语言编写,可以将 `#include <iostream>` 改为 `#include <stdio.h>`,将 `using namespace std;` 删除,并将 `cout` 改为 `printf`。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)