gpt4 book ai didi

java - BigInteger 和 BigDecimal 的平方根和++ 运算符

转载 作者:行者123 更新时间:2023-12-02 03:02:46 27 4
gpt4 key购买 nike

是否有现成的 Java 库用于对 BigInteger 和 BigDecimal 对象进行操作?

我想使用平方根和++ 运算符。

谢谢

附注应该使用 BigInteger.add() 而不是++,我明白了。BigInteger 的平方根怎么样?

最佳答案

BigInteger不可变的。这使得像++这样的东西- 运算符(operator)在概念上是不可能的。您无法更改给定 BigInteger 的值,就像你不能用 String 做到这一点一样.

递增

您始终必须创建一个新的 BigInteger保存增量值(当然,您可以将 BigInteger 的引用存储在同一个变量中)。

编辑:正如评论中指出的,“递增”看起来像:

BigInteger result = a.add(BigInteger.ONE);

a = a.add(BigInteger.ONE);

请注意,这两行都不会更改 BigInteger 的值其中a原本指向。最后一行创建一个 BigInteger 并将对其的引用存储在 a 中。 .

计算平方

您可以计算 BigInteger 的平方像这样:

BigInteger a = BigInteger.valueOf(2);
BigInteger a_square = a.multiply(a); // a^2 == a * a

BigInteger a_square = a.pow(2);

平方根

代码取自https://gist.github.com/JochemKuijpers/cd1ad9ec23d6d90959c549de5892d6cb 。它使用简单的二分法和巧妙的上限。请注意a.shiftRight(x)相当于 a / 2^x (仅适用于非负数,但这就是我们处理的全部)

BigInteger sqrt(BigInteger n) {
BigInteger a = BigInteger.ONE;
BigInteger b = n.shiftRight(5).add(BigInteger.valueOf(8));
while (b.compareTo(a) >= 0) {
BigInteger mid = a.add(b).shiftRight(1);
if (mid.multiply(mid).compareTo(n) > 0) {
b = mid.subtract(BigInteger.ONE);
} else {
a = mid.add(BigInteger.ONE);
}
}
return a.subtract(BigInteger.ONE);
}

使用运算符而不是方法

C++那样的运算符重载在Java中是不可能的。

关于java - BigInteger 和 BigDecimal 的平方根和++ 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42204941/

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