Skip to content

Commit 3855ec8

Browse files
authored
Merge pull request #16 from CrumbleZ/master
Performance improvements
2 parents c382c74 + 53238d7 commit 3855ec8

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed
Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
# Sieve of Eratosthenes
2-
# David Eppstein, UC Irvine, 28 Feb 2002
2+
# Originaly made by : David Eppstein, UC Irvine, 28 Feb 2002
3+
# Performance improvements : Gabriel Freitas, 7 Oct 2017
34

4-
from __future__ import generators
5+
from itertools import count
56

67
def eratosthenes():
7-
'''Yields the sequence of prime numbers via the Sieve of Eratosthenes.'''
8-
D = {} # map composite integers to primes witnessing their compositeness
9-
q = 2 # first integer to test for primality
10-
while 1:
11-
if q not in D:
12-
yield q # not marked composite, must be prime
13-
D[q*q] = [q] # first multiple of q not already marked
14-
else:
15-
for p in D[q]: # move each witness to its next multiple
16-
D.setdefault(p+q,[]).append(p)
17-
del D[q] # no longer need D[q], free memory
18-
q += 1
8+
"""Yields the sequence of prime numbers via the Sieve of Eratosthenes"""
9+
yield 2 # force yield the first prime number
10+
11+
D = {} # map composite integers to primes witnessing their compositeness
12+
for q in count(start=3, step=2):
13+
if q not in D:
14+
yield q # not marked composite, must be prime
15+
D[q*q] = [q] # first multiple of q not already marked
16+
else:
17+
for p in D[q]: # move each witness to its next odd multiple
18+
D.setdefault(2*p+q,[]).append(p)
19+
del D[q] # no longer need D[q], free memory

0 commit comments

Comments
 (0)