Implementdouble sqrt(double x)
andx >= 0
.
Compute and return the square root of x.
Notice
You do not care about the accuracy of the result, we will help you to output results.
Have you met this question in a real interview?
Yes
Example
Givenn
=2
return1.41421356
class Solution {
public:
/
**
* @param x a double
* @return the square root of x
*/
double sqrt(double x) {
// Write your code here
double eps = 1e-12;
double res = x;
while (abs(res * res - x) > eps) {
res = (res + x / res) / 2;
}
return res;
}
};