Python: Range() 最大尺寸;动态的还是静态的?

2022-01-24 00:00:00 python overflow range

问题描述

我对 python 还是很陌生,所以我照常通过 Project Euler 来解决我脑海中的逻辑问题.

I'm quite new to python, so I'm doing my usual of going through Project Euler to work out the logical kinks in my head.

基本上,我需要尽可能大的列表大小,即 range(1,n),而不会溢出.

Basically, I need the largest list size possible, ie range(1,n), without overflowing.

有什么想法吗?


解决方案

看看内置模块源码

总结:如果列表中的元素多于有符号长整数,您将收到溢出错误.在 32 位 Python 上是 2**31 - 1,在 64 位 Python 上是 2**63 - 1.当然,即使是低于该值的值,您也会收到 MemoryError.

Summary: You'll get an OverflowError if the list has more elements than can be fit into a signed long. On 32bit Python that's 2**31 - 1, and on 64 bit Python that's 2**63 - 1. Of course, you will get a MemoryError even for values just under that.

相关文章