I would like to share the fact that the fastest way with which I found generating prime numbers in a range is to use the sympy symbolic library :
import sympy def all_primes(start, end): return list(sympy.sieve.primerange(start, end))
The sympy.sieve.primerange() function returns a generator, so we need list() convert it to a list.
Here is an example of the performance difference between this and the already highly optimized answer that is currently most supported in this thread:
import sympy def get_primes_python(start, stop): dct = {x: True for x in list(range(start, stop+1))} x = start while x ** 2 <= stop: if dct[x]: y = x ** 2 while y <= stop: dct[y] = False y += x x += 1 lst = [] for x, y in dct.items(): if y: lst.append(x) return lst def get_primes_sympy(start, stop): return list(sympy.sieve.primerange(start, stop))
In [2]: %timeit test.get_primes_python(1, 10**7) 1 loop, best of 3: 4.21 s per loop In [3]: %timeit test.get_primes_sympy(1, 10**7) 10 loops, best of 3: 138 ms per loop
source share