牛顿迭代法推导

367

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool isPerfectSquare(int num) {
// 初始的值用num
double x0 = num;
while (true) {
// 牛顿迭代法找零点
double x1 = (x0 + num / x0) / 2;
if (x0 - x1 < 1e-6) {
break;
}
x0 = x1;
}
int x = (int) x0;
if (x * x == num) return true;
return false;
}
};

69

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int mySqrt(int x) {
if (x == 0) {
return 0;
}
// 初始的值用x
double x0 = x;
while (true) {
// 牛顿迭代法找零点
double x1 = (x0 + x / x0) / 2;
if (x0 - x1 < 1e-7) {
break;
}
x0 = x1;
}
return (int) x0;
}
};