學過數值分析的都知道牛頓迭代法


令f(x) = x2-a;
那么上式就變成:
xn+1 =xn-(xn2-a)/(2*xn)=(xn+a/xn)/2
實現的代碼如下,簡單優美,收斂快。
public class Solution {
public int sqrt(int x) {
if(x==0) return 0;
if(x<=2) return 1;
int result = x/2;
while(true){
int next = (result+x/result)/2;
if(next>=result){
break;
}
else{
result = next;
}
};
return result;
}
}
public int sqrt(int x) {
if(x==0) return 0;
if(x<=2) return 1;
int result = x/2;
while(true){
int next = (result+x/result)/2;
if(next>=result){
break;
}
else{
result = next;
}
};
return result;
}
}