MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / sieve_er

Function sieve_er

maths/primelib.py:95–135  ·  view source on GitHub ↗

input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. >>> sieve_er(8) [2, 3, 5, 7] >>> sieve_er(-1) Traceback (most recent call last): ... AssertionError: 'N'

(n)

Source from the content-addressed store, hash-verified

93
94
95def sieve_er(n):
96 """
97 input: positive integer 'N' > 2
98 returns a list of prime numbers from 2 up to N.
99
100 This function implements the algorithm called
101 sieve of erathostenes.
102
103 >>> sieve_er(8)
104 [2, 3, 5, 7]
105 >>> sieve_er(-1)
106 Traceback (most recent call last):
107 ...
108 AssertionError: 'N' must been an int and > 2
109 >>> sieve_er("test")
110 Traceback (most recent call last):
111 ...
112 AssertionError: 'N' must been an int and > 2
113 """
114
115 # precondition
116 assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2"
117
118 # beginList: contains all natural numbers from 2 up to N
119 begin_list = list(range(2, n + 1))
120
121 ans = [] # this list will be returns.
122
123 # actual sieve of erathostenes
124 for i in range(len(begin_list)):
125 for j in range(i + 1, len(begin_list)):
126 if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
127 begin_list[j] = 0
128
129 # filters actual prime numbers.
130 ans = [x for x in begin_list if x != 0]
131
132 # precondition
133 assert isinstance(ans, list), "'ans' must been from type list"
134
135 return ans
136
137
138# --------------------------------

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected