Find the Integer sqrt
November 21, 2024Less than 1 minute
Find the Integer sqrt
public class sqrt {
public static void main(String[] args) {
System.out.println(binarySearch(24)); //4
System.out.println(newton(24)); //4
}
public static int binarySearch(int x){
int index = -1;
int left = 0, right = x;
while(left <= right){
int mid = left + (right - left) / 2;
if(mid * mid <= x){
index = mid;
left = mid + 1;
} else{
right = mid - 1;
}
}
return index;
}
public static int newton(int x) {
if (x == 0) return 0;
return (int) sqrt1(x,x);
}
public static double sqrt1(double i, int x) {
double res = (i+ x/i)/2;
if(res == i){
return i;
} else {
return sqrt1(res, x);
}
}
}