如何使用range()在Python中迭代大数?

2024-10-01 17:34:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用Python中的range()函数迭代一个大数,比如600851475143。但每当我运行这个程序时,它就会给我一个溢出错误。 我使用了以下代码-

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

我试过很多次了,但都不行!


Tags: 函数代码in程序forinputraw错误
3条回答

如果索引是长数字,请使用itertools.islice()

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

Python 3的range()也可以处理Python long。

简化为您的案例:

for j in islice(count(1), num - 1):

尽管xrange似乎实现了您想要的目标,但它无法处理这么大的数字。您可能需要使用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).

不用,趁着

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

相关问题 更多 >

    热门问题