Description
Implement int sqrt(int x)
.
Compute and return the square root of X.
Example
sqrt (3) = 1
sqrt (4) = 2
sqrt (5) = 2
sqrt (10) = 3
Challenge
O (log (x))
Test instructions: To find the square root of a given number, if you use a general method, such as a dichotomy, you need to consider the scope of the int type, do not overflow. The best method when Newton iterative method. The code is as follows:
Public classSolution {/** * @paramX:an Integer *@return: The sqrt of x*/ Public intsqrtintx) {//Write your code here//Newton's iterative method to find square root Doublep=2.0; DoublePre=0; while(Math.Abs (P-pre) >1e-6) {Pre=p; P= (p+x/p)/2.0; } return(int) p; }}
On the application principle of Newton iterative method on square root, see blog: http://www.matrix67.com/blog/archives/361
141. SQRT (x) "Newton iterative method for square root by Java"