|
1 | 1 | # 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 |
3 | 4 |
|
4 |
| -from __future__ import generators |
| 5 | +from itertools import count |
5 | 6 |
|
6 | 7 | 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