Bloomberg L.P. Interview Question: Approximate the square root o... | Glassdoor

Interview Question

Software Engineer Interview(Student Candidate)

Approximate the square root of a number using binary search.

Answer

Interview Answer

2 Answers

2

double sqrt(double no)
{
#define PRECISION 0.00001
     double l = 1, h = no, m = 0;
while(h - l > PRECISION)
{
m = l + (h - l) / 2;
if(m * m - no > PRECISION)
h = m;
else
l = m;
}
}
}

PB on Oct 7, 2014
0

Java version:
double sqrt(double n) {
    double low = 1;
    double high = n;
    double middle = 0;

    while((high - low) > DELTA) {
        middle = low + (high - low) / 2;
        double v = middle * middle;
        if(v - n > DELTA) {
            high = middle;
        }
        else {
            low = middle;
        }
    }
    return middle;
}

Anonymous on Nov 30, 2014

Add Answers or Comments

To comment on this, Sign In or Sign Up.