Skip to content

Commit 1c3e41e

Browse files
committed
Implementation of sieve of eratosthenes
1 parent 161a983 commit 1c3e41e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Author: OMKAR PATHAK
2+
# Created at: 16th August 2017
3+
4+
# Sieve of Eratosthenes is one of the efficient algorithms to find all the prime numbers upto n, where n can be
5+
# upto 10 million. This algorithm is very efficient and fast and hence is preferred by many competitive programmers.
6+
7+
# Algo:
8+
# 1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).
9+
# 2. Initially, let p equal 2, the first prime number.
10+
# 3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list.
11+
# These numbers will be 2p, 3p, 4p, etc.; note that some of them may have already been marked.
12+
# 4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise,
13+
# let p now equal this number (which is the next prime), and repeat from step 3.
14+
# When the algorithm terminates, all the numbers in the list that are not marked (i.e are True) are prime.
15+
16+
def sieve_of_eratosthenes(n):
17+
''' function to find and print prime numbers upto the specified number
18+
19+
:param n: upper limit for finding all primes less than this value
20+
'''
21+
primes = [True] * (n + 1)
22+
p = 2 # because p is the smallest prime
23+
24+
while(p * p <= n):
25+
# if p is not marked as False, this it is a prime
26+
if(primes[p]) == True:
27+
# mark all the multiples of number as False
28+
for i in range(p * 2, n + 1, p):
29+
primes[i] = False
30+
31+
p += 1
32+
33+
# getting all primes
34+
primes = [element for element in range(2, n) if primes[element]]
35+
36+
return primes
37+
38+
def get_code():
39+
""" returns the code for the current class """
40+
import inspect
41+
return inspect.getsource(sieve_of_eratosthenes)

0 commit comments

Comments
 (0)