Meta interview question

How to implement Sqrt(double k) efficiently?

Interview Answers

Anonymous

4 Feb 2012

binary search is not a good approach, too slow. compare to that newton's method is simple and fast. double sqrt_newton(double v) { double x, nx = 1; while (abs(nx - x) > 1e-9) { x = nx; nx = (v / x + x) / 2; } return nx; }

2

Anonymous

3 Apr 2012

double sqrt2(double num) { double i = 0, j = num, mid; if(j 0.00001) { if(mid*mid > num) j = mid; else i = mid; mid = (i+j)/2.0; } return mid; }

2

Anonymous

11 Jan 2012

You could also use Newton's Method. It might be a bit (just a bit) less efficient, but it will work with every function, not just sqrt. en.wikipedia.org/wiki/Newton's_method

1

Anonymous

30 Dec 2011

Binary search, start with reasonable range and shrinking the range until precision level is satisfied

Anonymous

19 Jan 2012

i came up with a iterative algorithm bu having problem with the precision. for example, i get to this solution 2.236068 instead of 2.23606798 for sqrt(5) using double numbers, any ideas why?