【问题标题】:Is there an upper bound to BigInteger? [duplicate]BigInteger 有上限吗? [复制]
【发布时间】:2012-10-02 15:21:09
【问题描述】:

可能重复:
What does BigInteger having no limit mean?

BigInteger 的 Javadoc 没有定义任何最大值或最小值。但是,它确实说:

(强调)

不可变的任意精度整数

是否存在这样的最大值,即使在理论上也是如此?还是BigInteger 的运作方式根本不同,以至于实际上没有除了计算机上可用的内存量之外没有最大值?

【问题讨论】:

  • 理论上没有限制。
  • 可能重复的可接受答案未指定BigInteger的理论限制;或者,如果它真的没有,它不会解释原因。相反,它只是说如果有 个最大值,则它永远不会影响您当前的内存限制。
  • 它可能以 2 为底,因此最大值为 (2 ^ 32) ^ Integer.MAX_VALUE 以 2 为底。
  • @Ran, BigInteger.valueOf(2).pow(500500) 为我返回了一些东西。
  • @Ran,“不返回任何内容”在 Java 中没有任何意义。

标签: java biginteger


【解决方案1】:

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

诚然,这取决于实现,而不是规范的一部分。


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

BigInteger 必须支持 -2Integer.MAX_VALUE (不包括)到 +2Integer.MAX_VALUE (不包括)范围内的值,并且可能支持范围之外的值在那个范围内。

实现说明:当结果超出-2Integer.MAX_VALUE(独家)到+2@的支持范围时,BigInteger 构造函数和操作抛出ArithmeticException 987654335@(独家)。

【讨论】:

  • 由于这些值用作无符号int 值,最大值更像(2^32)^Integer.MAX_VALUE * 10^Integer.MAX_VALUE,因为它也可以缩放。
  • @PeterLawrey 你确定 BigInteger 有刻度吗? (BigDecimal 有一个)。
  • 由于整数 MAX_VALUE 约为 2^31,最大值不能保存在 32 位计算机内存中:) 所以内存是极限。
  • @SuzanCioc 你可以在 64 位机器上存储一个 2^32 整数数组(假设你有足够的 RAM)。
  • @assylias 好点。您还可以将new int[2^31-1] 存储在 64 位 JVM 中。它大约 8 GB,成本约为 40 美元。
【解决方案2】:

BigInteger 只有在你知道它不是小数的情况下才会使用,并且 长数据类型可能不够大。 BigInteger 的最大大小没有上限(与 电脑可以装)。

来自here

它是使用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;

来自the source

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

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

【讨论】:

    【解决方案3】:

    您要达到的第一个最大值是字符串的长度,即 231-1 位数字。它比 BigInteger 的最大值小得多,但恕我直言,如果不能打印,它就会失去很多价值。

    【讨论】:

    • 完全公平地说,您只需要更多的逻辑来打印它。
    • 如果可以使用多个字符串,您也可以使用多个 BigInteger。 ;)
    • 是的,但这会导致您的代码比打印例程更复杂。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2018-02-03
    • 2021-02-16
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多