-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSqRootBinary.java
44 lines (37 loc) · 1020 Bytes
/
SqRootBinary.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
public class SqRootBinary {
public static void main(String[] args)
{
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.println("Enter the Square");
long square = sc.nextInt();
long squareRoot = search(square);
System.out.println("Square Root of "+square+" is : "+squareRoot);
sc.close();
}
private static long search(long squareEle)
{
long s = 0;
long e = squareEle;
long mid = s + (e - s)/2;
long ans = -1;
while(s <= e)
{
long square = mid * mid;
if(square == squareEle)
{
return mid;
}
if(square > squareEle)
{
e = mid - 1;
}
if(square < squareEle)
{
ans = mid;
s = mid + 1;
}
mid = s + (e - s)/2;
}
return ans;
}
}