用c++求出100到200之间的素数,输出时一行打印5个素数
时间: 2023-05-13 11:05:29 浏览: 83
以下是代码实现:
```c
#include <stdio.h>
int is_prime(int n) {
if (n <= 1) {
return 0;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int count = 0;
for (int i = 100; i <= 200; i++) {
if (is_prime(i)) {
printf("%d ", i);
count++;
if (count % 5 == 0) {
printf("\n");
}
}
}
return 0;
}
```
输出结果如下:
```
101 103 107 109 113
127 131 137 139 149
151 157 163 167 173
179 181 191 193 197
199
```
希望能够帮到你!
相关问题
用c++编程求出100到200之间的素数,输出时一行打印5个素数
以下是代码:
```c
#include <stdio.h>
int is_prime(int n) {
if (n <= 1) {
return 0;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int count = 0;
for (int i = 100; i <= 200; i++) {
if (is_prime(i)) {
printf("%d ", i);
count++;
if (count % 5 == 0) {
printf("\n");
}
}
}
return 0;
}
```
输出结果:
```
101 103 107 109 113
127 131 137 139 149
151 157 163 167 173
179 181 191 193 197
199
```
用C++求 100~200 间的全部素数。结果逐行输出,要求每行输出 5 个
以下是使用C++编写的求100到200之间的全部素数并按每行5个进行输出的程序:
```cpp
#include <iostream>
bool isPrime(int number) {
if (number < 2) {
return false;
}
for (int i = 2; i <= number / 2; ++i) {
if (number % i == 0) {
return false;
}
}
return true;
}
int main() {
int count = 0;
for (int i = 100; i <= 200; ++i) {
if (isPrime(i)) {
std::cout << i << " ";
++count;
if (count % 5 == 0) {
std::cout << std::endl;
}
}
}
return 0;
}
```
这段代码中,首先定义了一个函数 `isPrime` 来判断一个数是否为素数。然后,在 `main` 函数中,使用循环遍历100到200之间的所有数,对每个数调用 `isPrime` 函数进行判断。如果是素数,则输出该数,并递增计数器 `count`。当 `count` 的值是5的倍数时,输出换行符。
希望对你有所帮助!如果还有其他问题,请随时提问。
相关推荐
![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)