Square root using Binary search concept GFG
package com.company;
public class SquareRoot {
// Finding the square root of a given number
// 1. Naive solution
public static int squareRoot(int x) {
// return (int)Math.sqrt(x);
int i = 0;
while(i * i <= x) {
i++;
}
return i - 1;
}
// Efficient solution
public static int getSquareRoot(int n) {
int low = 1; int high = n; int ans = -1;
while(low <= high) {
int mid = (low + high) / 2;
int sMid = mid * mid;
if(sMid == n) {
return mid;
}
else if(sMid > n) {
high = mid - 1;
}
else {
low = mid + 1;
ans = mid;
}
}
return ans;
}
public static void main(String[] args) {
System.out.println( getSquareRoot(10));
}
}
Comments
Post a Comment