Skip to content

Commit 7de5364

Browse files
Binary Search Sqrt with decimal places
1 parent ed4f0b0 commit 7de5364

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Binary Search/BSsqrt.java

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.kunal.maths;
2+
3+
public class BinarySearchSQRT {
4+
public static void main(String[] args) {
5+
int n = 40;
6+
int p = 3;
7+
8+
System.out.printf("%.3f", sqrt(n, p));
9+
}
10+
11+
// Time: O(log(n))
12+
static double sqrt(int n, int p) {
13+
int s = 0;
14+
int e = n;
15+
16+
double root = 0.0;
17+
18+
while (s <= e) {
19+
int m = s + (e - s) / 2;
20+
21+
if (m * m == n) {
22+
return m;
23+
}
24+
25+
if (m * m > n) {
26+
e = m - 1;
27+
} else {
28+
s = m + 1;
29+
root = m;
30+
}
31+
}
32+
double incr = 0.1;
33+
for (int i = 0; i < p; i++) {
34+
while (root * root <= n) {
35+
root += incr;
36+
}
37+
root -= incr;
38+
incr /= 10;
39+
}
40+
41+
return root;
42+
}
43+
}

0 commit comments

Comments
 (0)