题目:
Implementint sqrt(int x).
Compute and return the square root of x.
题意:
求他的平方根
解题思路:
第一种,调用Math.sqrt()API
第二种,类似于折半查找,通过比较 mid *mid 是否等于 x ,和折半思想差不多(mid 需要设为long类型,防止数据泄露)
第三种,使用牛顿法来解决,详细大家可以维基百科下或百度下都行 牛顿法 给出递推公式: res = (res+x/res)/2;
第四种,利用平方数的性质,连续 n个质数相加就一定是平方数,如 4 = 1 + 3; 9 = 1 + 3 + 5;....
下面给出代码:
/*
* 解法一,调用官方API
*/
public int sqrt(int x) {
if(x <= 0) {
return 0;
}
return (int)Math.sqrt(x);
}
/*
* 解法二 - 折半查找
*/
public int sqrt2(int x) {
if(x <= 0) {
return 0;
}
int low = 0;
int high = x;
while(low <= high) {
long mid = (low + high)/2;
if(mid * mid == x) {
return (int)mid;
}
else if(mid * mid < x) {
low = (int) (mid + 1);
}
else {
high = (int) (mid -1);
}
}
return high;
}
/*
* 解法三- 牛顿逼近法
*/
public int sqrt3(int x) {
long r = x;
while(r * r > x) {
r = (r + x/r)/2;
}
return (int) r;
}
/*
* 解法四 - 利用平方数的性质做答
*/
public int sqrt4(int x) {
int i = 1;
int res = 0;
while( x >= 0) {
x -= i;
res++;
i += 2;
}
return res-1;
}