I am looking for a fast and memory efficient way to find the next prime.
Input: An integer n
Output The first prime bigger then n
There is really nice code to print all primes smaller than n
at Fastest way to list all primes below N . My inefficient method currently finds all primes smaller than 2n
and then searches for the first prime bigger than n
by just looping through the list. Here is my current code.
import numpy
def primesfrom2to(n):
""" Input n>=6, Returns a array of primes, 2 <= p < n """
sieve = numpy.ones(n/3 + (n%6==2), dtype=numpy.bool)
for i in xrange(1,int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k/3 ::2*k] = False
sieve[k*(k-2*(i&1)+4)/3::2*k] = False
return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]
n=10**7
timeit next(x for x in primesfrom2to(2*n) if x > n)
1 loops, best of 3: 2.18 s per loop
n= 10**8
timeit next(x for x in primesfrom2to(2*n) if x > n)
1 loops, best of 3: 21.7 s per loop
This last test takes almost 1GB of RAM. Another problem with this code is that it just fails if $n = 10**10$ for example.
Can this problem be solved faster? Is there a way to get it to use less memory?