通过 long 变量移动 Java 的 BigInteger
Shifting BigInteger of Java by long variable
我知道 shiftLeft(int n)
和 shiftRight(int n)
方法 BigInteger
class 只接受 int 类型作为参数,但我必须将它移动 long
变量。有什么方法可以做到吗?
BigInteger
不支持 long
偏移量合适的值。我试过了
BigInteger a = BigInteger.valueOf(2).pow(Integer.MAX_VALUE);
我遇到了以下异常:
Exception in thread "main" java.lang.ArithmeticException: BigInteger would overflow supported range.
BigInteger 只能有 Integer.MAX_VALUE 位。右移超过此值将始终为零。左移除零以外的任何值都会溢出。
来自 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 亿个位集,超过您的可寻址内存。
yes the long variable might go up to 10^10
对于每个 10^10
位数,您需要 1.25 TB 的内存。对于这种大小的数据,您可能需要将其存储在堆之外,我们有一个库可以在不使用太多堆的情况下将如此多的数据保存在单个内存映射中,但是您需要在单个内存中释放这么多 space至少磁盘。 https://github.com/OpenHFT/Chronicle-Bytes
由于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 亿 个数字。
这是一个非常大的数字,需要一些时间才能完全精确地存储它。
我知道 shiftLeft(int n)
和 shiftRight(int n)
方法 BigInteger
class 只接受 int 类型作为参数,但我必须将它移动 long
变量。有什么方法可以做到吗?
BigInteger
不支持 long
偏移量合适的值。我试过了
BigInteger a = BigInteger.valueOf(2).pow(Integer.MAX_VALUE);
我遇到了以下异常:
Exception in thread "main" java.lang.ArithmeticException: BigInteger would overflow supported range.
BigInteger 只能有 Integer.MAX_VALUE 位。右移超过此值将始终为零。左移除零以外的任何值都会溢出。
来自 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 亿个位集,超过您的可寻址内存。
yes the long variable might go up to 10^10
对于每个 10^10
位数,您需要 1.25 TB 的内存。对于这种大小的数据,您可能需要将其存储在堆之外,我们有一个库可以在不使用太多堆的情况下将如此多的数据保存在单个内存映射中,但是您需要在单个内存中释放这么多 space至少磁盘。 https://github.com/OpenHFT/Chronicle-Bytes
由于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 亿 个数字。
这是一个非常大的数字,需要一些时间才能完全精确地存储它。