Search code examples
javabigintegerbinary-searchcomparison-operators

Relational Operation on two BigIntegers in Java


While trying to compute the square root of a BigInteger using BINARY SEARCH method,I was stuck in between as to how to comapre two BigIntegers for satisfying comparison operation. Like, I wanted to check for equality,greater than or lesser than conditions between two BigInteger variables.

Here is the wrong piece of code with rough idea of as to what I want to perform.Any efforts to resolve the issue would be appreciated.

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;
}

Solution

  • BigIntegers are Objects so you cannot compare their contents with relational operators such as >, and == won't compare contents; it will compare object references.

    However, BigInteger does implement Comparable<BigInteger>, so call compareTo instead.

    • For equality, use left.compareTo(right) == 0.
    • For less than, use left.compareTo(right) < 0.
    • For greater than, use left.compareTo(right) > 0.