forked from lizeyang18/byteDanceAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest08.java
More file actions
30 lines (28 loc) · 793 Bytes
/
test08.java
File metadata and controls
30 lines (28 loc) · 793 Bytes
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
package byteDance;
/**
* Created by lizeyang on 2020/5/12.
* 写一个函数,求平方根,函数参数为目标数字和精度
*/
public class test08 {
//二分法,此题可简化为实现平方根只求整数;时间复杂度O(logn)
public static double test(double target, double g) {
double l = 1;
double r = target;
double mid;
while (r - l > g) {
mid = (l + r) / 2;
if (mid * mid > target) {
r = mid;
} else {
l = mid;
}
}
return (l+r)/2;
}
public static void main(String[] args) {
double target = 4.1;
double g = 0.001;
System.out.println(test(target, g));
System.out.println(Math.sqrt(4.1));
}
}