Python OverflowError:无法将“long”放入索引=大小的整数中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4751725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:21:32  来源:igfitidea点击:

Python OverflowError: cannot fit 'long' into an index=sized integer

pythonrsaprimes

提问by

I want to generate two really large prime numbers using an algorithm I found online and changed slightly.

我想使用我在网上找到并略有更改的算法生成两个非常大的素数。

I get this error on line 5:

我在第 5 行收到此错误:

Python OverflowError: cannot fit 'long' into an index=sized integer 

My code:

我的代码:

import math
def atkin(end):  
    if end < 2: return []  
    lng = ((end/2)-1+end%2)   
    **sieve = [True]*(lng+1)**  
    for i in range(int(math.sqrt(end)) >> 1):
        if not sieve[i]: continue  
        for j in range( (i*(i + 3) << 1) + 3, lng, (i << 1) + 3):  
            sieve[j] = False  
    primes = [2]  
    primes.extend([(i << 1) + 3 for i in range(lng) if sieve[i]])  
    return primes

How can I fix my error?

我该如何修复我的错误?

If you know a better way to generate large primes, that would be helpful also.

如果您知道生成大素数的更好方法,那也会很有帮助。

采纳答案by Justin Peel

The following code demonstrates the problem that you are running into:

以下代码演示了您遇到的问题:

import sys
x = [True]*(sys.maxint+1)

which yields an OverflowError. If you instead do:

产生一个OverflowError. 如果你这样做:

x = [True]*(sys.maxint)

then you should get a MemoryError.

那么你应该得到一个MemoryError.

Here is what is going on. Python can handle arbitrarily large integers with its own extendible data type. However, when you try to make a list like above, Python tries to convert the number of times the small list is repeated, which is a Python integer, to a C integer of type Py_ssize_t. Py_ssize_t is defined differently depending on your build but can be a ssize_t, long, or int. Essentially, Python checks if the Python integer can fit in the C integer type before doing the conversion and raises the OverflowError if it won't work.

这是发生了什么。Python 可以使用自己的可扩展数据类型处理任意大的整数。但是,当您尝试创建像上面这样的列表时,Python 会尝试将小列表的重复次数(Python 整数)转换为 Py_ssize_t 类型的 C 整数。Py_ssize_t 的定义因构建而异,但可以是 ssize_t、long 或 int。本质上,Python 在进行转换之前会检查 Python 整数是否适合 C 整数类型,如果它不起作用,则会引发 OverflowError。

回答by 9000

Line 5 trues to allocate a really long list full of Truevalues. Probably your lngis too large to fit that list in memory?

第 5 行为 true 以分配一个非常长的充满True值的列表。可能您lng的文件太大而无法在内存中容纳该列表?

I was not able to exactly reproduce your error; in the worst case I ended up with just a MemoryErrorinstead.

我无法完全重现您的错误;在最坏的情况下,我最终只有一个MemoryError

Probably the algorithm is ok (though I can't bet), just try a smaller number.

可能算法没问题(虽然我不能打赌),只是尝试一个较小的数字。