java large numbers square root problem

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/dl962454/article/details/78447890
import java.util.*;
import java.math.*;
public class Main{
    static BigInteger cal(BigInteger x){
        BigInteger l = BigInteger.ONE ;
        BigInteger r = x ;
        BigInteger temp = BigInteger.ZERO ;
        while(!l.equals(r)){
            BigInteger mid = (l.add(r)).divide(BigInteger.valueOf(2)) ;
            if(temp.compareTo(BigInteger.ZERO)!=0&&temp.compareTo(mid)==0){
                break ;
            }else{
                temp = mid ;
            }
            if(temp.compareTo(BigInteger.ZERO)==0){
                temp = mid ;
            }
            if(mid.multiply(mid).compareTo(x)==1){
                r=mid ;
            }else{
                l=mid ;
            }
        }
        if(l.multiply(l).compareTo(x)==1){
            l=l.subtract(BigInteger.ONE) ;
        }
        return l;
    }
    public static void main(String[] args){
        Scanner cin=new Scanner(System.in);
        while(cin.hasNext()){
            BigInteger n=cin.nextBigInteger();
            System.out.println(cal(n));
        }
    }
}

Guess you like

Origin blog.csdn.net/dl962454/article/details/78447890