用筛选法就一百以内的素数
时间: 2023-09-25 16:12:22 浏览: 47
好的,我可以帮你用筛选法求出一百以内的素数。首先,我们可以创建一个长度为 101 的布尔型数组 primes,并将其全部初始化为 True,表示这些数均为素数。然后,我们从 2 开始,将其所有的倍数标记为非素数,即将其在 primes 中的对应位置赋值为 False。最后,我们遍历 primes 中所有值为 True 的位置,即可得到所有的素数。
以下是具体的 Python 代码实现:
```python
primes = [True] * 101
primes[0] = primes[1] = False
for i in range(2, int(101 ** 0.5) + 1):
if primes[i]:
for j in range(i * i, 101, i):
primes[j] = False
for k in range(101):
if primes[k]:
print(k, end=' ')
```
输出结果为:
```
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
```
相关问题
用c++筛选法求一百以内的素数
以下是用C++实现的筛选法求一百以内的素数的代码:
```c++
#include <iostream>
using namespace std;
int main() {
bool isPrime[101];
// 初始化数组,所有数都先认为是素数
for(int i = 2; i <= 100; i++) {
isPrime[i] = true;
}
// 筛选法
for(int i = 2; i <= 50; i++) {
if(isPrime[i]) {
// 将i的倍数都标记为非素数
for(int j = i * 2; j <= 100; j += i) {
isPrime[j] = false;
}
}
}
// 输出结果
for(int i = 2; i <= 100; i++) {
if(isPrime[i]) {
cout << i << " ";
}
}
return 0;
}
```
在上面的代码中,我们使用了一个布尔类型的数组`isPrime`来记录每个数字是否为素数。首先将数组中的所有元素都初始化为`true`,然后从2开始循环到50,对于每个素数i,将它的倍数都标记为非素数,最后输出结果即可。
用c语言写筛选法求一百以内的素数
以下是使用 C 语言编写的筛选法求 100 以内的素数的示例代码:
```c
#include <stdio.h>
int main()
{
int n = 100;
int is_prime[n+1];
// 初始化数组
for(int i = 2; i <= n; i++)
is_prime[i] = 1;
// 筛选素数
for(int i = 2; i*i <= n; i++)
{
if(is_prime[i])
{
for(int j = i*i; j <= n; j += i)
{
is_prime[j] = 0;
}
}
}
// 输出结果
printf("100 以内的素数:");
for(int i = 2; i <= n; i++)
{
if(is_prime[i])
printf("%d ", i);
}
return 0;
}
```
运行结果:
```
100 以内的素数: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
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)