Thursday, 15 April 2010

Memory error while calculating largest prime factor using python -



Memory error while calculating largest prime factor using python -

i trying find out largest prime number of big number, when run run error saying:

traceback (most recent phone call last): file "prb3.py", line 45, in print prime_factor() file "prb3.py", line 12, in prime_factor n in range(2,i): memoryerror

it works fine when run little number 13195

""" problem: prime factors of 13195 5, 7, 13 , 29. largest prime factor of number 600851475143 ? """ import math def prime_factor(): i=600851475143 factors=[] #list stores factors of number n in range(2,i): if(i%n==0 , (n%2!=0 , n!=2)): factors.append(n) """ have factors(which not numbers) next step find prime number factors list """ factor in factors: sqr_root=int(math.sqrt(factor)) """ take factor list , split numbers 3 sqroot(factor-1).if 0 remainder consider non prime , remove list.i apply factors sqr root greater 3.if less 3 split each number between 3 , factor-1. """ if(sqr_root<=3): num in range(3,factor-1): if(factor%num==0): factors.remove(factor) break else: num in range(3,sqr_root): if(factor%num==0): 1,1 top homecoming len(factors) if __name__ == "__main__": print prime_factor()

in python2, range() returns list. in case list contain 600851475141 int objects. since list big, can't fit in memory memory error

since don't need numbers in memory @ same time, seek using xrange() instead.

i think can simplify problem dividing out factors find them. eg.

n in xrange(2, i): while(i % n == 0 , (n % 2 != 0 , n != 2)): /= n print n if == 1: break

not needing loop 600851475141 times should create programme much faster

python

No comments:

Post a Comment