eratosthenes_使用Python中的Eratosthenes的Sieve算法找到所有小于或等于N的素数

本文介绍了Eratosthenes筛法,一种寻找小于或等于N的所有素数的古老算法。首先创建一个布尔数组,将每个位置设为True,然后从2开始,如果变量是素数,就将它的倍数标记为False。重复此过程,直到变量的平方大于N。最后,数组中True的位置即为素数。
摘要由CSDN通过智能技术生成

eratosthenes

As we all know that the prime number is an integer greater than 1 which is only divisible by 1 or itself. For example 2,3,5,7,11,.. etc. The value of N is given by the user. Before going to solve this problem, we will learn a little bit about the Sieve of Eratosthenes and it's an algorithm.

众所周知, 素数是大于1的整数,只能被1或自身整除。 例如2、3、5、7、11等。N的值由用户指定。 在解决此问题之前,我们将学习有关Eratosthenes筛网的知识 ,这是一种算法。

What is the Sieve of Eratosthenes?

什么是Eratosthenes筛?

It is a simple and ancient method for finding all Prime numbers less than or equal to N.

查找所有小于或等于N的素数是一种简单而古老的方法。

Algorithm to find Prime numbers by Sieve of Eratosthenes

通过Eratosthenes的Sieve查找素数的算法

  1. Initially, we will create a boolean array of size equal to the N and mark each position in the array True.

    最初,我们将创建一个布尔数组,其大小等于N ,并将数组中的每个位置标记为True。

  2. We initialize a variable p as 2. If the variable is prime then mark each multiple of number False in the array and update the variable p by increment.

    我们将变量p初始化为2。如果变量为质数,则在数组中标记数字False的每个倍数,并以增量方式更新变量p 。

  3. Repeat step 2 until the square of the variable p is less than or equal to N.

    重复步骤2,直到变量p的平方小于或等于N为止。

  4. Return, the elements in the array with True contains all Prime numbers.

    返回时,具有True的数组中的元素包含所有素数。

Implementation of the above algorithm using python program

使用python程序实现以上算法

# input the value of N
N=int(input("Input the value of N: "))

Primes=[True for k in range(N+1)]
p=2
Primes[1]=False
Primes[0]=False

while(p*p<=N):
    if Primes[p]==True:
        for j in range(p*p,N+1,p):
            Primes[j]=False
    p+=1

for i in range(2,N):
    if Primes[i]:
        print(i,end=' ')

Output

输出量

Input the value of N: 50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47


翻译自: https://www.includehelp.com/python/find-all-prime-numbers-less-than-or-equal-to-n-using-the-sieve-of-eratosthenes-algorithm.aspx

eratosthenes

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值