【问题标题】:Does BigInteger not have a maximum length ? If it has how can I find the maximum length of BigInteger datatype?BigInteger 没有最大长度吗?如果它有我怎样才能找到 BigInteger 数据类型的最大长度?
【发布时间】:2019-09-10 16:14:45
【问题描述】:

我们可以通过内置 MAX_VALUE 找到 Integer 的最大长度。但是对于 BigInteger 就不行了。

当我尝试对 BigInteger 使用 MAX_VALUE 时,它给出 >> 错误 >> 找不到符号变量 MAX_VALUE

public class ALL_datatype_length {
    public static void main(String [] args){

        byte a = Byte.MAX_VALUE;
        short b = Short.MAX_VALUE;
        int c = Integer.MAX_VALUE;
        long d = Long.MAX_VALUE;
        float e = Float.MAX_VALUE;
        double f = Double.MAX_VALUE;

        BigInteger g = BigInteger.MAX_VALUE;     //   >> Shows ERROR

        System.out.println(a + "\t\t\t\tMaximum value of byte");
        System.out.println(b + "\t\t\t\tMaximum value of short");
        System.out.println(c + "\t\t\tMaximum value of integer");
        System.out.println(d + "\t\tMaximum value of long");
        System.out.println(e + "\t\t\tMaximum value of float");
        System.out.println(f + "\t\tMaximum value of double");
    }
}

【问题讨论】:

  • BigInteger 的最大值由可用内存控制,所以不,没有最大值。

标签: java types biginteger maxlength


【解决方案1】:

假设您有内存,并且 JVM 将数组限制为 Integer.MAX_VALUE - 5 元素(请参阅 Do Java arrays have a maximum size?),那么 BigInteger 的最大值有一个全为 1 位的 mag 数组。

由于Integer.MAX_VALUE - 5 是 2,147,483,642,并且每个数组元素是 32 位 (int),所以 BigInteger 最多可以使用 68,719,476,544 位。

这意味着 20,686,623,727 位的十进制数。

这几乎是一样的无限。肯定没有定义的最大值。

【讨论】:

    【解决方案2】:

    来自 Javadoc:Class BigInteger

    BigInteger 必须支持 -2 Integer.MAX_VALUE(不包括)到 +2 Integer.MAX_VALUE(不包括)范围内的值,并且可能支持该范围之外的值。当 BigInteger 构造函数或方法将生成超出支持范围的值时,将引发 ArithmeticException。可能的素数范围是有限的,并且可能小于 BigInteger 的完全支持的正范围。范围必须至少为 1 到 2 500000000

    实施说明:

    在参考实现中,当结果超出 -2 Integer.MAX_VALUE(不包括)到 +2 Integer.MAX_VALUE 的支持范围时,BigInteger 构造函数和操作会抛出 ArithmeticException sup>(独家)。

    没有必要,但代码如下:

    // Same can be done for the negative value as well
    BigInteger twoBigInteger = BigInteger.valueOf(2);
    BigInteger intMaxBigInteger = BigInteger.valueOf(Integer.MAX_VALUE);
    BigInteger bigInteger = twoBigInteger.pow(intMaxBigInteger.intValue());
    System.out.println(bigInteger.intValue());
    

    例外:

    Exception in thread "main" java.lang.ArithmeticException: BigInteger would overflow supported range
        at java.math.BigInteger.reportOverflow(BigInteger.java:1084)
        at java.math.BigInteger.checkRange(BigInteger.java:1079)
        at java.math.BigInteger.<init>(BigInteger.java:1055)
        at java.math.BigInteger.shiftLeft(BigInteger.java:3174)
        at java.math.BigInteger.pow(BigInteger.java:2339)
        at MyClass.main(MyClass.java:7)
    
    

    【讨论】:

      猜你喜欢
      • 2015-06-12
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      相关资源
      最近更新 更多