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查找素数的算法
Initially, we will create a boolean array of size equal to the N and mark each position in the array True.
最初,我们将创建一个布尔数组,其大小等于N ,并将数组中的每个位置标记为True。
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 。
Repeat step 2 until the square of the variable p is less than or equal to N.
重复步骤2,直到变量p的平方小于或等于N为止。
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
eratosthenes