Skip to content

Commit d93c243

Browse files
committed
Add primes function from projecteuler
1 parent 002ef68 commit d93c243

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

maths.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,35 @@
1-
from itertools import product
1+
from itertools import count, product
2+
3+
4+
def primes():
5+
"""Yield prime numbers, starting with 2.
6+
7+
Algorithm by David Eppstein, Alex Martelli, and Tim Hochberg:
8+
http://code.activestate.com/recipes/117119/#c2
9+
10+
>>> p = primes()
11+
>>> [next(p) for _ in range(10)]
12+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
13+
"""
14+
yield 2
15+
# Map composites to primes witnessing their compositeness
16+
composites = {}
17+
# Skip even numbers
18+
for n in count(3, step=2):
19+
# We won't see n again, so we can delete its witness, if any
20+
prime_divisor = composites.pop(n, None)
21+
if prime_divisor is None:
22+
# n is prime
23+
yield n
24+
# Record n as a divisor of its square
25+
composites[n ** 2] = 2 * n
26+
else:
27+
# n is composite
28+
# Move the witness to a new multiple
29+
x = n + prime_divisor
30+
while x in composites:
31+
x += prime_divisor
32+
composites[x] = prime_divisor
233

334

435
def reordered_digit_map(exponents, base=2):

0 commit comments

Comments
 (0)