Python OverflowError:无法适应“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 整数)转换为 Py_ssize_t 类型的 C 整数。 Py_ssize_t 根据您的构建而定义不同,但可以是 ssize_t、long 或 int。本质上,Python 在进行转换之前会检查 Python 整数是否适合 C 整数类型,如果无法转换则引发 OverflowError。
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 行 true 分配一个充满
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.