-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP69.java
More file actions
76 lines (64 loc) · 2.01 KB
/
P69.java
File metadata and controls
76 lines (64 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
69. x 的平方根
https://leetcode-cn.com/problems/sqrtx/description/
https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/53/math/116/
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:
输入: 4
输出: 2
示例 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
*/
public class P69 {
public static void main(String[] args) {
System.out.println("------P69------");
Solution solution = new Solution();
System.out.println(solution.mySqrt(8));
System.out.println(solution.sqrt(8.0, 0.000000001));
System.out.println("------P69------");
}
}
class Solution {
// http://www.matongxue.com/madocs/205.html
// https://www.cnblogs.com/Matrix_Yao/archive/2009/07/28/1532883.html
public int mySqrt(int x) {
int count = 0;
long n = x;
// (x(n+1)) = (xn) - (f(xn) / f'(xn))
while (n * n > x) {
n = (n + x / n) >> 1; // same as ÷ 2
count++;
}
System.out.println(count);
return (int) n;
}
/**
* 牛顿迭代法求平方根
*
* @param number 求值的数
* @param accuracy 精度
* @return Double
*/
public static double sqrt(double number, double accuracy) {
// 第一个猜测值
double guess = number / 2;
int count = 0;
if (number < 0) {
return Double.NaN;
}
// 当两个猜测的差值大于精度即return
while (Math.abs(guess - (number / guess)) > accuracy) {
// 迭代公式推导而成
guess = (guess + (number / guess)) / 2;
count++;
System.out.printf("try count = %d, guess = %f\n", count, guess);
}
System.out.printf("final result = %f\n", guess);
return guess;
}
}