Interview Question

Interview

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

Answer

Interview Answer

5 Answers

1

here is the code: #include<stdio.h> 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)); } }

Seckin on Aug 4, 2010
0

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

Dah on Oct 12, 2010
0

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; }

bellpeace on Nov 18, 2010
0

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 on Nov 20, 2011
0

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

Dmitry on Aug 24, 2015

Add Answers or Comments

To comment on this, Sign In or Sign Up.