Meta Interview Question

Implement "double sqrt(double x)" in C++.

Interview Answers

Anonymous

Aug 5, 2010

here is the code: #include double sq(double x){ double mx = 32000; double mn = 0; while(mx - mn > 1e-9){ double md = (mx + mn) / 2; if(md * md > x) mx = md; else mn = md; } return mx; } int main(){ while(1){ double db; scanf("%lf",&db); printf("%lf\n",sq(db)); } }

2

Anonymous

Oct 12, 2010

Would it be more efficient in some cases to also check md*md == x?

Anonymous

Nov 21, 2011

Seckin's algorithm is correct (it is called binary search) but it not very efficient. it will get you on average one bit of precision for each iteration. the babylonian method will double the number of correct bits at each iteration. It can be found here: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots

Anonymous

Aug 24, 2015

Algorithm above is partially correct since it would not give results for "0 < x < 1"

Anonymous

Nov 18, 2010

Here is my contribution: double sq(double x){ double sqr = 0; double offset = 1; while (1) { if (sqr*sqr == x) { break; } else if (sqr*sqr > x){ sqr -= offset; offset /= 10; } sqr += offset; } return sqr; }