Sieve of Eratosthenes: Difference between revisions
→Infinite generator with a faster algorithm: change "bps.next()" to "next(bps)" for Python 2/3 compatibility; cleaned up code for speed...
m (→wheel version with optional prime list suppression: optimized the computing of J².) |
GordonBGood (talk | contribs) (→Infinite generator with a faster algorithm: change "bps.next()" to "next(bps)" for Python 2/3 compatibility; cleaned up code for speed...) |
||
Line 3,683:
===Infinite generator with a faster algorithm===
The adding of each discovered prime's incremental step info to the mapping should be '''''postponed''''' until the prime's ''square'' is seen amongst the candidate numbers, as it is useless before that point. This drastically reduces the space complexity from <code>O(n)</code> to <code>O(sqrt(n/log(n)))</code>, in ''<code>n</code>'' primes produced, and also lowers the run time complexity quite low ([http://ideone.com/
<lang python>def primes():
yield 2
p =
q = p *
sieve = {} # into sieve dict
n = 9 # the initial candidate number
while True:
if n not in sieve: # is not a multiple of previously recorded primes
if n < q:
yield n # n is prime
else:
p = next(bps); q = p * p # advance base prime and next prime to be put
else:
s = sieve.pop(n); nxt = n + s # n is composite, advance
n += 2 # work on odds only
▲ sieve[next] = step # next non-marked multiple of a prime
import itertools
def primes_up_to(limit):
|