Java中两个BigIntegers的关系运算

Am_*_*ful 1 java biginteger binary-search comparison-operators

在尝试使用BINARY SEARCH方法计算BigInteger的平方根时,我陷入了如何使用两个BigIntegers来满足比较操作的问题.就像,我想检查两个BigInteger变量之间的相等,大于或小于条件.

这是错误的代码片段,粗略地了解我想要执行的内容.任何解决问题的努力都将受到赞赏.

public static BigInteger squareroot(BigInteger bi){
    //BigInteger bkl;
    BigInteger low,high,mid;
low=ONE;
high=bi.add(ZERO);
while(low<=high)
{
    mid =(low.add(high)).divide(new BigInteger("2"));
    if(mid.multiply(mid).equals(bi))
        return mid;
    if(mid.multiply(mid) > bi)
        high = mid -1 ;
    else
        low = mid + 1;
}
return mid;
}
Run Code Online (Sandbox Code Playgroud)

rge*_*man 5

BigIntegers是Objects所以你不能将它们的内容与关系运算符比较>,而==不会比较内容; 它将比较对象引用.

但是,BigInteger确实实现了Comparable<BigInteger>,所以请调用compareTo.

  • 为了平等,使用left.compareTo(right) == 0.
  • 少于,使用left.compareTo(right) < 0.
  • 大于,使用left.compareTo(right) > 0.