Try the following:
def getPrimes(maxnum): primes = [] for i in xrange(2, maxnum): is_mul = False for j in primes:
You should not run out of memory until you reach a very large number of primes. This way you don't have to worry about creating a list of multiples. Not sure if this is still considered a sieve.
Actually, this will not work for maxnum = 39312312323123123 . Using the type number theorem , we can estimate that there will be approximately 1,028,840,332,567,181 primes in this range.
As pointed out in this question, the maximum size of a python list on a 32-bit system is 536,870,912 . Therefore, even if you do not have enough memory, you still cannot complete the calculation.
You should not have this problem with a 64-bit system.
2 ** 64 => 18446744073709551616
Using the math from the above question (2 ** 64) / 8 , the maximum number of items in the list will be 2,305,843,009,213,693,951 , which is more than the estimated number of primes you will encounter.
Edit:
To avoid memory problems, you can save a list of primes in a file on your hard drive. Keep one stroke in a 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():
At the end, you will have a file on your hard drive containing all your primes.
Okay, so it will be pretty slow, but you will not run out of memory. You can do this faster by increasing the speed with which you can read / write files (e.g. RAID ).