Python OverflowError:无法将“long"放入索引=大小的整数中 [英] Python OverflowError: cannot fit 'long' into an index=sized integer
问题描述
我想使用我在网上找到并稍有改动的算法生成两个非常大的素数.
I want to generate two really large prime numbers using an algorithm I found online and changed slightly.
我在第 5 行收到此错误:
I get this error on line 5:
Python OverflowError: cannot fit 'long' into an index=sized integer
我的代码:
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.
推荐答案
以下代码演示了您遇到的问题:
The following code demonstrates the problem that you are running into:
import sys
x = [True]*(sys.maxint+1)
产生一个 OverflowError
.如果您改为这样做:
which yields an OverflowError
. If you instead do:
x = [True]*(sys.maxint)
那么你应该得到一个MemoryError
.
这是怎么回事.Python 可以使用自己的可扩展数据类型处理任意大的整数.但是,当您尝试创建像上面这样的列表时,Python 会尝试将小列表的重复次数(Python 整数)转换为 Py_ssize_t 类型的 C 整数.Py_ssize_t 的定义因构建而异,但可以是 ssize_t、long 或 int.本质上,Python 在进行转换之前会检查 Python 整数是否适合 C 整数类型,如果它不起作用,则会引发 OverflowError.
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 OverflowError:无法将“long"放入索引=大小的整数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!