Skip to content

Instantly share code, notes, and snippets.

@sdpatil
Created August 14, 2017 15:39
Show Gist options
  • Save sdpatil/1d1c896ce03691decaa798a05271c0a5 to your computer and use it in GitHub Desktop.
Save sdpatil/1d1c896ce03691decaa798a05271c0a5 to your computer and use it in GitHub Desktop.
Compute the integer square root
/**
* Problem is given a integer find largest integer whose square is less than or equal to k
* Ex. Given 16 return 4 or given 15 return 3
*
* Solution :- Basic idea is if square of a number x is less than k then no number less than x would
* be the answer same way if square of x is more than k then you can ignore all numbers more than x.
* You can use binary search to solve this problem
*/
public class SquareRootCalculator {
public int squareRoot(int k) {
if (k <= 1)
return k;
int start = 0;
int end = k;
int answer = 0;
while (start <= end) {
int mid = start + (end - start) / 2;
//Since we need to deal with approximation (Not exact match we dont have == condition in search
if (mid <= k / mid) {
start = mid + 1;
answer = mid;
} else
end = mid - 1;
}
return answer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment