Implement int sqrt(int x).java
Compute and return the square root of x.code
公式推導:ip
在x<sub>0</sub>處的值是f(x<sub>0</sub>),這個點的切線能夠表示爲get
y = f`(x<sub>0</sub>)*(x - x<sub>0</sub>)+f(x<sub>0</sub>)io
求得當y = 0的時候,x<sub>1</sub> = x<sub>0</sub> - f(x<sub>0</sub>)/f`(x<sub>0</sub>)class
由此迭代下去能夠收斂di
牛頓法的形象解法view
public class Solution { public int sqrt(int x) { double t = x; double lamda = 1; double oldT = t; while (Math.abs(t * t - x) >= 0.000000000000001 && lamda > 0.00000000000000000000001) { t = (t + x / t) / 2; lamda /= 2; oldT = t; } return (int) (t); } }