Write a function to compute the square root of a number without using any built-in functions.
Anónimo
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; }