-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsquare_root_of_an_integer.java
86 lines (69 loc) · 2.19 KB
/
square_root_of_an_integer.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
Given an integer x, find square root of it. If x is not a perfect square, then return floor(√x).
*/
//time complexity O(n^2)
/**
*
* @author shivam
*/
import java.util.Scanner;
public class square_root_of_a_number {
public static void main(String[] args) {
//code
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number whose square root(or floor of sqrt(x)) you want ");
int x = sc.nextInt();
if (x == 0 || x == 1) {
System.out.println(x);
return;
}
int low = 0, high = x;
while (low <= high) {
int mid = (low + (high - low) / 2);
if (mid * mid == x) {
System.out.println("Answer="+mid);
break;
}
else if (mid * mid < x && (mid+1) * (mid + 1) > x) {
System.out.println("Answer="+mid);
break;
}
else if (mid * mid < x && (mid + 1) * (mid + 1) <= x) {
low = mid + 1;
//System.out.println("low2 " + low);
}
else {
if((high)*(high)==x )
{
System.out.println("Answer="+(high));
break;
}
high = mid - 1;
//System.out.println("high1 " + high);
if((high)*(high)<=x )
{
System.out.println("Answer="+(high));
break;
}
if((high-1)*(high-1)<x )
{
System.out.println("Answer="+(high-1));
break;
}
}
}
}
}
/*
OUTPUT
run:
Enter a number whose square root(or floor of sqrt(x)) you want
529
Answer=23
BUILD SUCCESSFUL (total time: 2 seconds)
run:
Enter a number whose square root(or floor of sqrt(x)) you want
36
Answer=6
BUILD SUCCESSFUL (total time: 1 second)
*/