Facebook Interview Question: Write a function to compute t... | Glassdoor

## Interview Question

Front End Engineer, Infrastructure Interview Menlo Park, CA

# Write a function to compute the square root of a number

without using any built-in functions.

3

They want you to remember your numerical methods/analysis class in college, specifically Newton's method. Or at the least, remember that the square root of a number as calculated by a computer is just a really close guess. Of course, this is like asking a civil engineer questions about lumberjacking. Great question if you're writing a math library for a new language, stupid interview question if you're making a glorified MySpace.

Bjorg on May 13, 2012
8

A good way to do this is using binary search. Given the number, assume your square root is between 0 and n.
Make 0 as your left and n as right. Compute their mid, if mid is less than square root i.e. mid * mid is less than n, assign left as mid as right as mid and continue looping.

double sqroot(double n)
{
double tol = 0.00001;
double left = 0;
double right = n;
double sq = 0;
double res=1;

while (right-left > tol)
{
sq = (left + right) / 2;
cout << "Low:" << left << " High: " << right << " MID:" << sq << endl;
if(sq*sq < n) // n is greater
left = sq;
else right = sq;
}
return sq;
}

Fayyaz on May 26, 2012