File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package Searches ;
2+
3+ import java .util .Scanner ;
4+
5+ /**
6+ * Given an integer x, find the square root of x. If x is not a perfect square, then return floor(√x).
7+ * <p>
8+ * For example,
9+ * if x = 5, The answer should be 2 which is the floor value of √5.
10+ * <p>
11+ * The approach that will be used for solving the above problem is not going to be a straight forward Math.sqrt().
12+ * Instead we will be using Binary Search to find the square root of a number in the most optimised way.
13+ *
14+ * @author sahil
15+ */
16+ public class SquareRootBinarySearch {
17+
18+ /**
19+ * This is the driver method.
20+ *
21+ * @param args Command line arguments
22+ */
23+ public static void main (String args []) {
24+ Scanner sc = new Scanner (System .in );
25+ System .out .print ("Enter a number you want to calculate square root of : " );
26+ int num = sc .nextInt ();
27+ long ans = squareRoot (num );
28+ System .out .println ("The square root is : " + ans );
29+ }
30+
31+ /**
32+ * This function calculates the floor of square root of a number.
33+ * We use Binary Search algorithm to calculate the square root
34+ * in a more optimised way.
35+ *
36+ * @param num Number
37+ * @return answer
38+ */
39+ private static long squareRoot (long num ) {
40+ if (num == 0 || num == 1 ) {
41+ return num ;
42+ }
43+ long l = 1 ;
44+ long r = num ;
45+ long ans = 0 ;
46+ while (l <= r ) {
47+ long mid = l + (r - l ) / 2 ;
48+ if (mid == num / mid )
49+ return mid ;
50+ else if (mid < num / mid ) {
51+ ans = mid ;
52+ l = mid + 1 ;
53+ } else {
54+ r = mid - 1 ;
55+ }
56+ }
57+ return ans ;
58+ }
59+ }
You can’t perform that action at this time.
0 commit comments