Here's a slightly more memory efficient version (and: the correct sieve, not trial units). In principle, instead of storing an array of all numbers and deleting those that are not primary, it stores an array of counters - one for each stroke found - and skips them in front of the proposed prime number. Thus, it uses storage proportional to the number of primes, and not to the highest value.
import itertools def primes(): class counter: def __init__ (this, n): this.n, this.current, this.isVirgin = n, n*n, True
You will notice that primes() is a generator, so you can save the results in a list or use them directly. Here are the first n prime numbers:
import itertools for k in itertools.islice (primes(), n): print (k)
And, for completeness, here is a timer for measuring performance:
import time def timer (): t, k = time.process_time(), 10 for p in primes(): if p>k: print (time.process_time()-t, " to ", p, "\n") k *= 10 if k>100000: return
Just in case you are interested, I also wrote primes() as a simple iterator (using __iter__ and __next__ ), and it worked at almost the same speed. They surprised me too!
Jules May Jan 05 '17 at 19:55 2017-01-05 19:55
source share