How do I iterate over large numbers in Python using range()? [duplicate]

寵の児 提交于 2019-12-23 09:56:00

问题


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!


回答1:


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



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




回答3:


don't use for, use while

counter = long(1)
while counter < num:
    ...


来源:https://stackoverflow.com/questions/15725506/how-do-i-iterate-over-large-numbers-in-python-using-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!