Find square root of number upto given precision

Given a positive number n and precision p, find the square root of number upto p decimal places using binary search. Examples:

Input : number = 50, precision = 3
Output : 7.071

Input : number = 10, precision = 4
Output : 3.1622

Approach : 1) As the square root of number lies in range 0 <= squareRoot <= number, therefore, initialize start and end as : start = 0, end = number. 2) Compare the square of mid integer with the given number. If it is equal to the number, then we found our integral part, else look for the same in left or right side depending upon the scenario. 3) Once we are done with finding the integral part, start computing the fractional part. 4) Initialize the increment variable by 0.1 and iteratively compute the fractional part upto p places. For each iteration, increment changes to 1/10th of it’s previous value. 5) Finally return the answer computed.

class Solution {
    public static double sqrt(int n, int precision) {
        double start = 0.0, end = n;
        while (end - start > Math.pow(10, -precision)) {
            double mid = start + (end - start) / 2;
            if (mid * mid <= n)
                start = mid;
            else
                end = mid;
        }
        return start;
    }
}

Last updated