5

I want to iterate a large number such as 600851475143 using the range() function in Python. But whenever I run the program it gives me an OverflowError. I have used the following code -

um = long(raw_input())
for j in range(1,num):
....

I have tried it many times but it is not working!

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Soham Banerjee
  • 79
  • 1
  • 2
  • 7
  • What do you want to do with these numbers? You almost certainly want `xrange` instead of range – Thomas Mar 31 '13 at 01:50
  • @Thomas The number is too big for `xrange` – jamylak Mar 31 '13 at 01:50
  • You may want to try this: [range too large][1] [1]: http://stackoverflow.com/questions/9816603/range-is-too-large-python Hope it helps – Student Mar 31 '13 at 01:55
  • 1
    *Hint*: If you think the solution involves `range(1, 600851475143)`, you might need a different solution. That's going to be rather painfully slow. – nneonneo Mar 31 '13 at 01:57

3 Answers3

4

Use itertools.islice() if your indices are long numbers:

from itertools import islice, count
islice(count(start, step), (stop-start+step-1+2*(step<0))//step)

Python 3's range() can handle python longs as well.

Simplified to your case:

for j in islice(count(1), num - 1):
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

Although xrange seems to achieve what you want, it can't handle numbers that large. You may need to use this recipe from here

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).

jamylak
  • 128,818
  • 30
  • 231
  • 230
1

don't use for, use while

counter = long(1)
while counter < num:
    ...
Yarkee
  • 9,086
  • 5
  • 28
  • 29