## DEV Community is a community of 695,394 amazing developers

We're a place where coders share, stay up-to-date and grow their careers. # Sieve of Eratosthenes Deepak Raj
Skilled in Data Science, Machine Learning, Deep Learning, As Well As Web Development Knowledge. React ❤️ to encourage Author. ### Topic: Sieve of Eratosthenes

In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite the multiples of each prime, starting with the first prime number, 2.

Example:-

``````Input : n = 10
Output : 2 3 5 7

Input : n = 20
Output: 2 3 5 7 11 13 17 19
``````

### Steps to Implement sieve of Eratosthenes

• Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).

• Initially, let p equal 2, the first prime number.

• Starting from p2, count up in increments of p and mark each of these numbers greater than or equal to p2 itself in the list. These numbers will be p(p+1), p(p+2), p(p+3), etc..

• Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.

### Implementation of Sieve of Eratosthenes in Python3.

``````def get_primes(n):
m = n+1
#numbers = [True for i in range(m)]
numbers = [True] * m #EDIT: faster
for i in range(2, int(n**0.5 + 1)):
if numbers[i]:
for j in range(i*i, m, i):
numbers[j] = False
primes = []
for i in range(2, m):
if numbers[i]:
primes.append(i)
return primes

print(get_primes(25))
``````