Python Overfloeserror:不能适合' long'进入索引=大小的整数
我想使用我在网上找到的算法生成两个非常大的素数,并略微更改。
我在第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
如何解决错误?
如果您知道一种更好的产生大量素数的方法,那也会有所帮助。
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:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下代码演示了您遇到的问题:
它产生了
OverflowerRor
。如果您这样做:那么您应该获得
MemoryError
。这是正在发生的事情。 Python可以使用自己的扩展数据类型处理任意大型整数。但是,当您尝试列出上面的列表时,Python试图将重复的小列表重复的次数(即Python Integer)转换为py_ssize_t类型的c Integer。 py_ssize_t的定义不同,取决于您的构建,但可以是ssize_t,long或int。从本质上讲,Python检查Python Integer是否可以在进行转换之前适合C Integer类型,并在不起作用的情况下提高溢流器。
The following code demonstrates the problem that you are running into:
which yields an
OverflowError
. If you instead do:then you should get a
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.
第5行Trues分配一个非常长的列表,其中包含
true
值。可能您的lng
太大了,无法在内存中适合该列表吗?我无法准确地重现您的错误;在最坏的情况下,我最终只获得了
memoryError
。大概可以使用算法(尽管我不能敢打赌),只需尝试一个较小的数字即可。
Line 5 trues to allocate a really long list full of
True
values. Probably yourlng
is too large to fit that list in memory?I was not able to exactly reproduce your error; in the worst case I ended up with just a
MemoryError
instead.Probably the algorithm is ok (though I can't bet), just try a smaller number.