统计1-100之间的素数个数。 直接输出素数个数。 用c++语言
时间: 2024-05-24 16:11:54 浏览: 11
#include <stdio.h>
int main() {
int count = 0; // 记录素数个数
for (int i = 2; i <= 100; i++) {
int is_prime = 1; // 标记是否为素数
for (int j = 2; j < i; j++) {
if (i % j == 0) {
is_prime = 0;
break;
}
}
if (is_prime) {
count++;
}
}
printf("1-100之间的素数个数为:%d\n", count);
return 0;
}
相关问题
用c++ 统计101-200之间有多少个素数,并输出所有素数。
以下是用C++统计101-200之间的素数并输出的代码示例:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main() {
int count = 0;
cout << "素数列表:" << endl;
for (int i = 101; i <= 200; i++) {
if (isPrime(i)) {
cout << i << " ";
count++;
if (count % 10 == 0) {
cout << endl;
}
}
}
cout << "\n总共有 " << count << " 个素数。" << endl;
return 0;
}
```
用c++语言找出1-100之间的素数
可以使用以下代码实现:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int count = 0;
for (int i = 2; i <= 100; i++) {
bool isPrime = true;
for (int j = 2; j <= sqrt(i); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
cout << i << " ";
count++;
}
}
cout << endl << "Total: " << count << " prime numbers." << endl;
return 0;
}
```
输出结果为:
```
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Total: 25 prime numbers.
```
该程序使用了两层循环,外层循环遍历2到100之间的整数,内层循环判断该数是否为素数。素数是指只能被1和本身整除的正整数,因此内层循环从2开始遍历到该数的平方根,如果该数能被其中任意一个整数整除,则说明该数不是素数。最后统计一共有多少个素数,并将它们输出。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)