Try this:
def getPrimes(maxnum):
primes = []
for i in xrange(2, maxnum):
is_mul = False
for j in primes: # Try dividing by all previous primes
if i % j == 0:
is_mul = True # Once we find a prime that i is divisible by
break # short circuit so we don't have to try all of them
if not is_mul: # if we try every prime we've seen so far and `i`
primes.append(i) # isn't a multiple, so it must be prime
return primes
You shouldn't run out of memory until you get to a very large number of primes. This way you don't have to worry about creating a list of multiples. Not sure if this still counts as the sieve though.
Actually, this won't work for maxnum = 39312312323123123
. Using the Prime number theorem we can estimate that there will be approximately 1,028,840,332,567,181
prime numbers in that range.
As pointed out in this question the maximum size of a python list on a 32-bit system is 536,870,912
. So even if you don't run out of memory, you still won't be able to finish the calculation.
You shouldn't have that problem with a 64-bit system though.
2 ** 64 => 18446744073709551616
Using the math from the aforementioned question (2 ** 64) / 8
, the maximum number of elements in a list would be 2,305,843,009,213,693,951
which is greater than the estimated number of primes you will encounter.
Edit:
To avoid memory issues, you could store your list of primes in a file on the hard disk. Store one prime per line and read the file every time you check a new number.
Maybe something like this:
primes_path = r'C:\temp\primes.txt'
def genPrimes():
for line in open(primes_path, 'r'):
yield int(line.strip())
def addPrime(prime):
primes_file = open(primes_path, 'a')
primes_file.write('%s\n' % prime)
primes_file.close()
def findPrimes(maxnum):
for i in xrange(2, maxnum):
is_mul = False
for prime in genPrimes(): # generate the primes from a file on disk
if i % prime == 0:
is_mul = True
break
if not is_mul:
addPrime(i) # append the new prime to the end of your primes file
At the end, you would have a file on your hard drive that contained all your primes.
Ok, so this would be pretty slow, but you wouldn't run out of memory. You could make it faster by increasing the speed at which you can read/write files (like RAID).