This is my code for finding primes using the Sieve of Eratosthenes.
list = [i for i in range(2, int(raw_input(\"Compute primes up to what number? \"))+1)]
The following one-liner is not related at all to your code:
def primes(n):
return set(range(2,n))-{c for i in range(2,n) for c in range(2*i,n,i)}
Like your code, this is still not really the Sieve of Eratosthenes because, for example, it will futilely try to cross off multiples of 6
and 9
etc. Nevertheless it still runs significantly faster than most other Sieve look-alikes for values less than a million or more, since for small N there are "about as many" primes as non-primes (the fraction of numbers < N that are prime is 1/log(N)
).
Heavily modified from source, possibly less efficient than original: http://codeblog.dhananjaynene.com/2011/06/10-python-one-liners-to-impress-your-friends/
Here is the most compact true sieve I have come up with so far. This performs surprisingly well.
def pgen(n): # Sieve of Eratosthenes generator
np = set() # keeps track of composite (not prime) numbers
for q in xrange(2, n+1):
if q not in np:
yield q
np.update(range(q*q, n+1, q))
>>> list(pgen(100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
79, 83, 89, 97]
This slightly more complex version is the fastest I have seen:
def pgen(n): # Sieve of Eratosthenes generator by Dan Salmonsen
yield 2
np = set()
for q in xrange(3, n+1, 2):
if q not in np:
yield q
np.update(range(q*q, n+1, q+q))
Here is a true sieve as a list comprehension:
def primes(n):
sieve = set(sum([range(q*q, n+1, q+q) for q in odds], []))
return [2] + [p for p in odds if p not in sieve]
>>> primes(100)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
79, 83, 89, 97]