操纵二的大幂的有效方法
对 2 的幂进行编码的最有效方法是通过整数的位移位。
<代码>1 << n 给我 2^n
但是,如果我有一个数字大于 int
或 long
中允许的最大值code>,我可以使用什么来有效地操纵 2 的幂?
(我需要能够对数字执行加法、乘法、除法和模运算)
The most efficient way to code powers of two is by bit shifting of integers.
1 << n
gives me 2^n
However, if I have a number that is larger than the largest value allowed in an int
or a long
, what can I use to efficiently manipulate powers of 2?
(I need to be able to perform addition, multiplication, division and modulus operations on the number)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是你需要的吗?
这是n=1000时的结果,
Is this what you need?
This is the result when n=1000,
您需要对“二的幂”执行哪些操作?例如,如果只是除法和乘法,您可以只保留所讨论的 2 的幂的
log2
,并对其使用减法和加法。如果不知道您想要什么类型的“操纵”,就不可能就如何有效“操纵”给出好的建议;-)。What operations do you need to perform on your "powers of two"? If it's only division and multiplication, for example, you can just keep the
log2
of the powers of two in question, and use subtraction and addition on them instead. Without knowing what kinds of "manipulate" you want, it's impossible to give good suggestions on how to efficiently "manipulate";-).简单:
long
:-)如果您不介意浮点数,
double
可以精确地表示 2 到 2^1023 的所有幂。否则,这取决于你正在做什么样的“操纵”。
Easy:
long
:-)If you don't mind floating-point,
double
can exactly represent all powers of 2 up to 2^1023.Otherwise, it depends on what kind of "manipulation" you're doing.
看起来像
java.math.BigInteger
就是您所需要的。它有
mod
、shiftLeft
、shiftRight
,当然还有add
、multiply
、减
和除
。它是一个不可变的类型(alaString
),所以也许它不是最终最有效的做事方式,但除非你已经证明它是一个性能问题,否则我不会担心它。Looks like
java.math.BigInteger
is what you need.It has
mod
,shiftLeft
,shiftRight
, and of courseadd
,multiply
,subtract
anddivide
. It's an immutable type (alaString
), so perhaps it's not the ultimate most efficient way of doing things, but unless you've provably identified it as a performance problem, I wouldn't worry about it.需要准确吗?
否则,您可以将 is 表示为 long 乘以 2 的 int 次方。
示例:
x = 15 * 2^123
Does it need to be accurate?
Otherwise you can represent is as a long multiplied by an two to the power of an int.
Example:
x = 15 * 2^123