Meta Interview Question

Use basic arithmetic operations (+-*/) to implement sqrt function.

Interview Answers

Anonymous

Mar 26, 2012

public static double sqrt(double a) { //firstly check if a is non-negative value if(aprecision) { double mid = (start+end)/2; double midSqr = mid*mid; if(midSqr==a) return mid;//we find the exact sqrt value! else if(midSqr

2

Anonymous

Apr 9, 2012

Both solutions are bad. The real solution is use a fixpoint iteration to find the square root of d. a_k = (a_k + d/a_k) / 2

Anonymous

Apr 9, 2012

Sorry a_(k+1) =

Anonymous

Oct 22, 2012

This is best answered with Newtons Method of Sqrt in C++ double sqrt(double x) int est1; int est2 = x-1; for(int i =0 i< 10; i++){ est1 = est2 est2 = est1 -(est*est-x)/(2*est) } return est2 where i is the iterations for accuracy so the higher the i value the better accuracy you will get

Anonymous

Dec 9, 2012

What about taylor expansion, you hardcode it, but i think it's ok to... 1+(n-1)*(1/2.0-1/8* (n-1)^2+1/16 (n-1)^3-5/128 (n-1)^4+7/256 (n-1)^5

Anonymous

Apr 6, 2012

public static double sqrt(double a) { return a^(1/2); }