用长变量移位Java的BigInteger



我知道BigInteger类有shiftLeft(int n)shiftRight(int n)方法,它只接受int类型作为参数,但我必须通过long变量来移动它。有什么方法可以做到吗?

BigInteger只能是Integer。MAX_VALUE碎片。向右移动比这个多,结果总是0。左移除0以外的任何值都将被溢出。

来自Javadoc

 * BigInteger constructors and operations throw {@code ArithmeticException} when
 * the result is out of the supported range of
 * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
 * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive).

如果你需要超过20亿比特来表示你的值,你就会遇到一个相当常见的问题,BigInteger不是为它设计的。

如果你需要在非常大的范围内进行位操作,我建议使用BitSet[],这将允许20亿个比特集中的20亿个,超过你的可寻址内存。

是的,长变量可以达到10^10

对于每个10^10位,您需要1.25 TB的内存。对于这种大小的数据,您可能需要将其存储在堆外,我们有一个库可以将这么多数据保存在单个内存映射中,而无需使用太多堆,但您至少需要在单个磁盘上有这么多空闲空间。https://github.com/OpenHFT/Chronicle-Bytes

BigInteger不支持适合long移位量的值。我试着

BigInteger a = BigInteger.valueOf(2).pow(Integer.MAX_VALUE);

,我得到了下面的异常:

线程"main"中的异常java.lang. arithmelexexception: BigInteger将超出支持范围。

由于2 ^ X等于10 ^ (X * ln(2) / ln(10)),我们可以计算X = 10 ^ 10:

2 ^ (10 ^ 10) = 10 ^ 3,010,299,956.63981195...
              = 10 ^ 3,010,299,956 * 10 ^ 0.63981195...
              = 4.3632686... * 10 ^ 3,010,299,956

意思是4后面跟着超过3 十亿个数字。

这是一个非常大的数字,将它存储到完全精确需要一些时间

最新更新