I’m currently trying to find the largest prime number contained within another large number.
maxlen = 1024
for i in range(1023, -1, -1):
maxlen -= 1
number = ""
for k in range(maxlen, -1, -1):
number = pi[k] + number
if isprime(number) == True:
print number
isprime() is a function that checks if the number is a prime (pretty standard).
this works pretty well up to a certain point where I get a MemoryError.
This is not because the number checked by the function is too large since it happens around the 6th run of the first for loop.
I’ve already tried gc.enable() and gc.collect() without any positive result.
Does anyone have an idea how to fix this?
Edit: definition of pi and isprime() as per request:
f = open("/root/number", "r")
pi = f.read()
f.close()
where the file “number” contains the original number in which I’d like to find the prime.
def isprime(n):
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
Traceback:
Traceback (most recent call last):
File "./primal.py", line 36, in <module>
if isprime(number) == True:
File "./primal.py", line 24, in isprime
for x in range(3, int(n**0.5)+1, 2):
MemoryError
Use
xrangeinstead ofrange, most importantly inisprime, here:xrangedoesn’t create the whole list in memory, while range does, but you are not using the results after you iterated over them.Another tip: just test for
isprime(n), there is no need to see if it is equal toTrue, that is whatifdoes. 🙂