Just to clarify, this is not a homework problem :)
I wanted to find primes for a math application I am building & came across Sieve of Eratosthenes approach.
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
i
only for i
up to root of n
i
to False
using x[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 np
def 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 primes
print(len(primes(100_000_000)))