Skip to content

Commit f336c40

Browse files
authored
Add implementation for square root using Binary Search (TheAlgorithms#2509)
Co-authored-by: sahil.samantaray <[email protected]>
1 parent 5b8bcf0 commit f336c40

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
}

0 commit comments

Comments
 (0)