使用C++输出101到200之间的素数。
时间: 2024-03-20 07:42:04 浏览: 23
以下是使用C++输出101到200之间的素数的代码:
```c++
#include <iostream>
using namespace std;
bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main() {
for (int i = 101; i <= 200; i++) {
if (isPrime(i)) {
cout << i << " ";
}
}
return 0;
}
```
输出结果为:101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199。
相关问题
c++输出1到n之间素数个数
以下是一个简单的 C++ 代码,可以输出 1 到 n 之间素数的个数:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int n) {
if (n <= 1) return false;
int sqrtn = sqrt(n);
for (int i = 2; i <= sqrtn; i++) {
if (n % i == 0) return false;
}
return true;
}
int countPrimes(int n) {
int count = 0;
for (int i = 2; i <= n; i++) {
if (isPrime(i)) count++;
}
return count;
}
int main() {
int n;
cout << "输入n的值:";
cin >> n;
cout << "1到" << n << "之间素数的个数为:" << countPrimes(n) << endl;
return 0;
}
```
该程序中的 `isPrime` 函数用于判断一个数是否为素数。对于一个大于 1 的自然数 n,如果其不是素数,则必定存在一个小于等于 sqrt(n) 的质因子,因此只需对 2 到 sqrt(n) 之间的数进行遍历即可判断 n 是否为素数。
在 `countPrimes` 函数中,我们遍历 2 到 n 之间的所有数,统计素数的个数。
最后在 `main` 函数中,我们通过用户输入 n 的值,输出 1 到 n 之间素数的个数。
c++求100到200之间的素数
以下是C++求100到200之间的素数的代码:
```c++
#include <iostream>
using namespace std;
int main() {
int i = 0, sum = 0;
for (i = 100; i <= 200; i++) {
int b = 0;
for (b = 2; b <= i; b++) {
if (i % b == 0)
break;
}
if (i == b) {
cout << "素数是" << i << endl;
sum += 1;
}
}
cout << "素数有" << sum << "个" << endl;
return 0;
}
```
输出结果为:
```
素数是101
素数是103
素数是107
素数是109
素数是113
素数是127
素数是131
素数是137
素数是139
素数是149
素数是151
素数是157
素数是163
素数是167
素数是173
素数是179
素数是181
素数是191
素数是193
素数是197
素数是199
素数有21个
```
相关推荐
![](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)