I am using Python 2.7 and I am getting the following error. How can I fix it?
for y in range(1, x/2):
OverflowError: range() result has too many items
# Largest Prime Factor prime = True x = 600851475143 pNum = 0 for y in range(2, x/2): if (x % y == 0): # Found a factor for z in range(2, y/2): # Checking factor for prime if (y % z == 0): # prime = False break if (prime == True): pNum = y prime = True print pNum
Try xrange in stead of range.
In python 2.x range() returns a list, which is limited in capacity (by both available memory and max long 2^64 -1 for 64-bit Py) and thus likely to produce OverflowError with large datasets.
So, the prescribed solution is to use xrange() which returns a generator which doesn't have a fixed capacity or bound by int or long numbers for indexing.
In python 2.x, range(1, n) create a list of n-1 items.
Use xrange unless you really need all that items at once.
According to xrange documentation:
CPython implementation detail: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (“short” Python integers), and also requires that the number of elements fit in a native C long. If a larger range is needed, an alternate version can be crafted using the itertools module: islice(count(start, step), (stop-start+step-1+2*(step<0))//step).
from itertools import islice, count prime = True x = 600851475143 pNum = 0 for y in islice(count(2), x/2-2): if (x % y == 0): # Found a factor for z in islice(count(2), y/2-2): # Checking factor for prime if (y % z == 0): # prime = False break if (prime == True): pNum = y prime = True print pNum