Using a bit of numpy
, I could find all primes below 100 million in a little over 2 seconds.
There are two key features one should note
- Cut out multiples of
i
only fori
up to root ofn
- Setting multiples of
i
toFalse
usingx[2*i::i] = False
is much faster than an explicit python for loop.
These two significantly speed up your code. For limits below one million, there is no perceptible running time.
import numpy as npdef primes(n): x = np.ones((n+1,), dtype=np.bool) x[0] = False x[1] = False for i in range(2, int(n**0.5)+1): if x[i]: x[2*i::i] = False primes = np.where(x == True)[0] return primesprint(len(primes(100_000_000)))