Find all Prime numbers less than or equal to N using the Sieve of Eratosthenes algorithm in Python

In this instructional exercise, we will figure out how to locate every single Prime number not exactly or equivalent to N by utilizing the Sieve of Eratosthenes calculation in Python programming language?

As we as a whole realize that a prime number is a number more noteworthy than 1 which is just distinct by 1 or itself. For example 2,3,5,7,11,.. and so forth. The estimation of N is given by the client. Prior to going to take care of this issue, we will get familiar with a tad about the Sieve of Eratosthenes and it’s a calculation.

What is the Sieve of Eratosthenes?

It is a basic and old technique for discovering every single Prime number not exactly or equivalent to N.

The calculation to discover Prime numbers by Sieve of Eratosthenes

At first, we will make a boolean cluster of a size equivalent to the N and imprint each position in the exhibit True.

We introduce a variable p as 2. In the event that the variable is prime, at that point mark each numerous of number False in the cluster and update the variable p by the increase.

Rehash stage 2 until the square of the variable p is not exactly or equivalent to N.

Return, the components in the exhibit with True contains every Prime number.

Usage of the above calculation utilizing python program:

# 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

Leave a Comment

error: Alert: Content is protected!!