Facing MemoryError in Python
https://softwareengineering.stackexchange.com/questions/269961
-
06-10-2020 - |
Question
I wrote a program to find prime factors of a number.
When I give a large number(600851475143) as input, MemoryError
pops up.
Below is the code:
def fact(a):
factors = []
for i in range(1,a+1):
if a%i == 0:
factors.append(i)
return factors
num = raw_input(">> ")
#600851475143
a = b = []
a = fact(long(num))
for i in range(0,len(a)):
b = fact(a[i])
if len(b) <= 2:
print a[i]
From browsing I came to know that Python makes use of Computer memory - RAM. I am using Python in Unbuntu without changing its configuration. Should I change anythig to work on 64-bit machine. Or should I use any additional function(s) to get around this error
Solution
There are various ways to measure the memory used by your program, and you may be able increase per-user limits or something.
However, you don't need to allocate that memory in the first place, since you can just generate the sequence without storing it all:
def fact(a):
"just return a generator for the sequence you want"
return (i for i in xrange(1,a+1) if a % i == 0)
Note that you can also iterate directly over sequences without needing to index them repeatedly:
for b in fact(long(num)):
print b