I found this highly optimised implementation of the Sieve of Eratosthenes for Python on Stack Overflow. I have a rough idea of what it's doing but I must admit the details of it's workings elude me.
I would still like to use it for a little project (I'm aware there are libraries to do this but I would like to use this function).
Here's the original:
'''
Sieve of Eratosthenes
Implementation by Robert William Hanks
https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188
'''
def sieve(n):
"""Return an array of the primes below n."""
prime = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool)
for i in range(3, int(n**.5) + 1, 3):
if prime[i // 3]:
p = (i + 1) | 1
prime[ p*p//3 ::2*p] = False
prime[p*(p-2*(i&1)+4)//3::2*p] = False
result = (3 * prime.nonzero()[0] + 1) | 1
result[0] = 3
return numpy.r_[2,result]
What I'm trying to achieve is to modify it to return all primes below n
starting at x
so that:
primes = sieve(50, 100)
would return primes between 50 and 100. This seemed easy enough, I tried replacing these two lines:
def sieve(x, n):
...
for i in range(x, int(n**.5) + 1, 3):
...
But for a reason I can't explain, the value of x
in the above has no influence on the numpy array returned!
How can I modify sieve()
to only return primes between x
and n