Created
February 18, 2018 01:11
-
-
Save mbadros/55ca3f41813072be66796a22d2eedd5a to your computer and use it in GitHub Desktop.
Highly optimized sieve of Erastosthenes in Python from https://codereview.stackexchange.com/questions/42420/sieve-of-eratosthenes-python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy | |
| def sieve8(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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment