I am working on below problem:
Given an integer, how do you find the square root of the number without using any built-in function?
private static double computeSquareRootBinarySearch(double x, double precision) {
double start = 0;
double end = x / 2 + 1;
double mid = (start + ((end - start) / 2));
double prevMid = 0;
double diff = Math.abs(mid - prevMid);
while ((mid * mid != x) && (diff > precision)) {
if (mid * mid > x) {
end = mid;
} else {
start = mid;
}
prevMid = mid;
mid = (start + end) / 2;
diff = Math.abs(mid - prevMid);
}
return mid;
}
I came up with above binary search algo but wanted to see if there is any optimization I can do in above algorithm?
Math.abs()
, then why not also useMath.sqrt()
? \$\endgroup\$Abs(...)
by yourself. Otherwise, why theses operations in themid
anddiff
initialization? And, it's not stated that the result must be the closest greater possible. So, why+ 1
in theend
init? \$\endgroup\$