一種經典的求解思路就是使用二分法。javascript
可使用二分法的緣由是y=x^2是單調遞增的java
遞歸版本ui
function sqrt(n){
return _sqrt(0,n)
function _sqrt(left,right){
if(Math.abs((left-right))<1e-9){
return left
}
let mid = (left+right)/2
let y = mid * mid
if(y>n){
return _sqrt(left,mid)
}else if(y==n){
return mid
}else{
return _sqrt(mid,right)
}
}
}
複製代碼
迭代版本spa
function sqrt(n){
if(n===0 || n===1){
return n;
}
let left = 0;
let right = n;
let mid;
let y;
while(Math.abs((right-left))>1e-9){
mid = (left+right)/2;
y = mid * mid;
if(y>n){
right = mid;
}else if(y===n){
return mid
}else{
left = mid;
}
}
return left
}
複製代碼
牛頓迭代法的原理.net
function sqrt(n){
let x = n;
while(x * x >n)
x = (x+n/x)/2
return x
}
複製代碼