forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquareRootOfInteger.java
More file actions
63 lines (53 loc) · 1.96 KB
/
SquareRootOfInteger.java
File metadata and controls
63 lines (53 loc) · 1.96 KB
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
package com.interviewbit.binary_search;
import com.util.LogUtil;
/**
* Implement int sqrt(int x).
* <p>
* Compute and return the square root of x.
* <p>
* If x is not a perfect square, return floor(sqrt(x))
* <p>
* Example :
* <p>
* Input : 11
* Output : 3
*
* @author neeraj on 2019-07-29
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
public class SquareRootOfInteger {
public static void main(String[] args) {
// for(int number=1;number<=1000;number++) {
// nearestSqrt = number;
// LogUtil.logIt("Square Root of " + number + " from \n library function ==> " +
// (int) Math.floor(Math.sqrt(number)) + " and from our custom function ==> " + sqrt(number));
// }
int number = 2147483647;
// System.out.println(Math.sqrt(number));
LogUtil.logIt("Square Root of " + number + " from \n library function ==> " +
(int) Math.floor(Math.sqrt(number)) + " and from our custom function ==> " + sqrt(number));
}
public static int sqrt(int a) {
return binarySearch(a, 1, a);
}
static int nearestSqrt = -1;
/**
* Here instead of doing mid*mid == numberWeAreSearchingFor
* we are doing mid = number/mid (Mathematically both are equivalent, but first one will cause StackOverflow error).
*/
public static int binarySearch(int numberWhoseSquareRootIsBeingSearched, int low, int high) {
if (low <= high) {
int mid = low + (high - low) / 2;
if (mid == numberWhoseSquareRootIsBeingSearched / mid) {
return mid;
} else if (mid > numberWhoseSquareRootIsBeingSearched / mid) {
return binarySearch(numberWhoseSquareRootIsBeingSearched, low, mid - 1);
} else {
nearestSqrt = mid;
return binarySearch(numberWhoseSquareRootIsBeingSearched, mid + 1, high);
}
}
return nearestSqrt;
}
}