Skip to content

Commit 3753953

Browse files
committed
Implement Sieve of Eratosthenes with unit tests
1 parent c127897 commit 3753953

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
sieve_eratosthenes.py
3+
4+
Implementation of the Sieve of Eratosthenes algorithm.
5+
6+
Depth First Search Overview:
7+
------------------------
8+
Is a simple, ancient algorithm for finding all prime numbers
9+
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
10+
the multiples of each prime, starting with the multiples of 2.
11+
12+
The sieve of Eratosthenes is one of the most efficient ways
13+
to find all of the smaller primes (below 10 million or so).
14+
15+
Time Complexity: O(n log log n)
16+
17+
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
18+
"""
19+
20+
def eratosthenes(end,start=2):
21+
if start < 2:
22+
start = 2
23+
primes = range(start,end)
24+
marker = 2
25+
while marker < end:
26+
for i in xrange(marker, end+1):
27+
if marker*i in primes:
28+
primes.remove(marker*i)
29+
marker += 1
30+
return primes
31+
32+

algorithms/tests/test_math.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import unittest
22
from ..math.extended_gcd import extended_gcd
3+
from ..math.sieve_eratosthenes import eratosthenes
34

45

56
class TestExtendedGCD(unittest.TestCase):
@@ -24,3 +25,15 @@ def test_extended_gcd(self):
2425
# Find extended_gcd of 50 and 15
2526
(a, b) = extended_gcd(50, 15)
2627
self.assertIs(50 * a + 15 * b, 5)
28+
29+
class TestSieveOfEratosthenes(unittest.TestCase):
30+
31+
def test_eratosthenes(self):
32+
rv1 = eratosthenes(-10)
33+
rv2 = eratosthenes(10)
34+
rv3 = eratosthenes(100,5)
35+
rv4 = eratosthenes(100,-10)
36+
self.assertEqual(rv1,[])
37+
self.assertEqual(rv2,[2, 3, 5, 7])
38+
self.assertEqual(rv3,[5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97])
39+
self.assertEqual(rv4,[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97])

0 commit comments

Comments
 (0)