-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqrtNewtons.java
48 lines (39 loc) · 885 Bytes
/
SqrtNewtons.java
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
package commonQuestions;
import java.util.ArrayList;
public class SqrtNewtons {
public static void main(String[] args) {
int n = 5;
//int result = sqrtNewtons(n, 0, 1+(n/2));
//System.out.println(result);
/* int low = 0;
int high = n;
while(low+1 < high) {
int mid = low + (high-low)/2;
if(mid*mid == n) {
System.out.println(mid);
break;
//return mid;
} else if(mid*mid > n) {
high = mid;
} else {
low = mid;
}
}
System.out.println(low);*/
}
public static int sqrtNewtons(int n, int low, int high) {
if(low == high || (low+1) == high) {
System.out.println(low);
return low;
}
int mid = low + (high-low)/2;
if(mid*mid == n) {
System.out.println(mid);
return mid;
} else if(mid*mid > n) {
return sqrtNewtons(n, low, mid);
} else {
return sqrtNewtons(n, mid, high);
}
}
}