gpt4 book ai didi

Java ArithmeticException BigInteger 会溢出支持的范围

转载 作者:行者123 更新时间:2023-11-29 07:41:37 26 4
gpt4 key购买 nike

我正在研究一种算法来检查数字是否为质数,并且需要处理非常大的数字,因此我正在使用 BigInteger 类。问题是抛出此异常ArithmeticException BigInteger 会溢出支持的范围

Exception in thread "main" java.lang.ArithmeticException: BigInteger would overflow supported range
at java.math.BigInteger.reportOverflow(Unknown Source)
at java.math.BigInteger.checkRange(Unknown Source)
at java.math.BigInteger.<init>(Unknown Source)
at java.math.BigInteger.shiftLeft(Unknown Source)
at java.math.BigInteger.pow(Unknown Source)
at Kitas.main(Kitas.java:118)

以及抛出异常的行:

b = BigInteger.valueOf(2).pow((int) (35*(Math.pow(2, counter))));

一旦计数器达到 26 的值,就会抛出异常。

最佳答案

(int) (35 * Math.pow(2, 26)) == (int) (2348810240d) = Integer.MAX_VALUE

结果是您尝试将 2 提高到的幂为 Integer.MAX_VALUE,因此结果将超过 Integer.MAX_VALUE 二进制数字。 BigInteger 不够大,存储这么大的数字是非常不切实际的。

Java 中没有任何内置的东西可以让您测试那么大的数字的素数。

关于Java ArithmeticException BigInteger 会溢出支持的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29547156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com