A modified version of the prime sieve. I actually doubt it could be implemented any faster, but I might be wrong:
from math import sqrt
def sieve(n):
"""
* A fast implementation of the prime sieve algorithm. Finds all prime numbers up to a given upper bound.
* Params:
* n: The upper bound.
* Return:
* A list of all prime numbers in [0, n].
* Implementation:
* Implements the sieve of Erasthotenes with a few optimisations for speed.
* We only delete multiples of numbers up to `int(sqrt(n))`. This suffices to find all prime numbers.
* We manipulate a list of boolean values, indexed by the number itself with the values denoting its primality. This is much faster than deleting elements in the list.
"""
if n < 2: return []
prime = [True]*(n + 1) #Initialise the list.
rt = int(sqrt(n))+1
for x in range(2, rt): #We only need to seive multiples of numbers <= to `n`.
if prime[x]:
for c in range(x*x, n + 1, x): prime[c] = False
return [idx for idx, p in enumerate(prime) if p][2:]