BigInteger有上限吗?

ast*_*eri 76 java biginteger

可能重复:
BigInteger没有限制意味着什么?

Javadoc for BigInteger没有定义任何最大值或最小值.但它确实说:

(重点补充)

不可变的任意精度整数

甚至在理论上是否存在这样的最大值?或者BigInteger操作方式是否根本不同,除了计算机上可用的内存量之外,实际上没有最大值?

ass*_*ias 71

数字保存在int[]- 数组的最大大小为Integer.MAX_VALUE.所以最大的BigInteger可能就是(2 ^ 32) ^ Integer.MAX_VALUE.

不可否认,这取决于实现,而不是规范的一部分.


在Java 8中,一些信息被添加到BigInteger javadoc中,给出了最小支持范围和当前实现的实际限制:

BigInteger必须支持范围-2Integer.MAX_VALUE(不包括)到+2Integer.MAX_VALUE(不包括)的值,并且可以支持该范围之外的值.

实现注意事项:当结果超出(独占)到(不包括)的支持范围时,BigInteger构造函数和操作抛出.ArithmeticException-2Integer.MAX_VALUE+2Integer.MAX_VALUE

  • 由于这些值用作无符号的`int`值,因此最大值更像是`(2 ^ 32)^ Integer.MAX_VALUE*10 ^ Integer.MAX_VALUE`,因为它也可以缩放. (5认同)
  • 由于整数MAX_VALUE约为2 ^ 31,因此最大值不能保留在32位计算机内存中:)因此,内存是极限。 (2认同)
  • @SuzanCioc你可以在64位机器上存储一个2 ^ 32个整数的数组(假设你有足够的RAM). (2认同)
  • @assylias好点.您还可以在64位JVM中存储`new int [2 ^ 31-1]`.它大约8 GB,大约40美元. (2认同)

emb*_*yle 20

只有当你知道它不是小数时才会使用BigInteger,并且有可能长数据类型不够大.BigInteger的最大大小没有上限(与计算机上的RAM一样大).

这里开始.

它使用以下方式实现int[]:

  110       /**
  111        * The magnitude of this BigInteger, in <i>big-endian</i> order: the
  112        * zeroth element of this array is the most-significant int of the
  113        * magnitude.  The magnitude must be "minimal" in that the most-significant
  114        * int ({@code mag[0]}) must be non-zero.  This is necessary to
  115        * ensure that there is exactly one representation for each BigInteger
  116        * value.  Note that this implies that the BigInteger zero has a
  117        * zero-length mag array.
  118        */
  119       final int[] mag;
Run Code Online (Sandbox Code Playgroud)

来自消息来源

来自维基百科的文章Arbitrary-precision arithmetic:

一些现代编程语言内置了对bignums的支持,而其他语言库则可用于任意精度的整数和浮点数学.这些实现通常使用可变长度的数字数组,而不是将值存储为与处理器寄存器的大小相关的固定数量的二进制位.


Pet*_*rey 11

你要击中的第一个最大值是一个字符串的长度,即2 31 -1位.它比BigInteger的最大值要小得多,但如果无法打印,它会失去很多价值.

  • 完全公平,你只需要更多的逻辑来打印它. (10认同)
  • 是的,但这会导致代码中的复杂性多于打印例程. (4认同)
  • 如果可以使用多个字符串,您也可以使用多个BigIntegers.;) (3认同)