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
range(1, a+1)
is attempting to create a list with 600851475143 elements. This is probably not what you want as each element will be an integer and each integer takes 4 bytes. (Also, this question isn't appropriate for Programmers as you really need a code review and to understand in particular how python works.) – Steven Burnap Jan 13 at 18:56xrange
, which is a generator that returns elements to thefor
loop as needed. That may not be the only issue you are having, though.) – Steven Burnap Jan 13 at 18:58