【问题标题】:Square Root and ++ Operators for BigInteger and BigDecimalBigInteger 和 BigDecimal 的平方根和 ++ 运算符
【发布时间】:2017-02-13 13:13:11
【问题描述】:

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

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

谢谢

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

【问题讨论】:

  • 你检查过这些类的文档吗?
  • 是的,不幸的是,我没有找到关于从 BigInteger 获得平方的消息
  • @sunny 如果你看我的回答,你会发现不需要专门的square() 方法。简单的乘法就可以了。
  • 对不起,我的意思是平方根。在一个问题中修复它

标签: java operator-overloading operators biginteger bigdecimal


【解决方案1】:

BigInteger不可变的。这使得它上面的++-operator 之类的东西在概念上是不可能的。您无法更改给定 BigInteger 的值,就像您无法使用 String 一样。

递增

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

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

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

a = a.add(BigInteger.ONE);

请注意,这两行都不会更改a 最初指向的BigInteger 的值。最后一行创建了一个new 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 中是不可能的。

【讨论】:

  • 增加BigInteger使用BigInteger result = a.add(BigInteger.ONE);
  • 谢谢你,明白了
  • 要完整,还要添加这个方形变体BigInteger result = a.pow(2);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 2011-05-23
  • 1970-01-01
相关资源
最近更新 更多