Maybe it is a stupid question, but i was wondering if you could provide the shortest source to find prime numbers with Python. I was also wondering how to find prime numbers
This uses more characters, but it's readable:
def primes_to(n):
cands = set(xrange(2, n))
for i in xrange(2, int(n ** 0.5) + 1):
for ix in xrange(i ** 2, n, i):
cands.discard(ix)
return list(cands)
A new way, similar to the above, but with less missed attempts at discard:
def primes_to(n):
cands = set(xrange(3, n, 2))
for i in xrange(3, int(n ** 0.5) + 1, 2):
for ix in xrange(i ** 2, n, i * 2):
cands.discard(ix)
return [2] + list(cands)