Using divide and conquer approach, or we can say using modified binarysearch technique we can calculate nearest perfect square of a given number
public class ClosestPerfectSquare {
public int getClosestPerfectSquare(int x) {
int min = findMinSquareRoot(x, 1, x);
int a = min * min;
int b = (min + 1) * (min + 1);
if (x - a < b - x) {
return a;
} else if (x - a > b - x) {
return b;
} else {
return x;
}
}
private int findMinSquareRoot(int x, int left, int right) {
if (left > right) {
return -1;
}
if (left * left <= x && x <= (left + 1) * (left + 1)) {
return left;
}
int mid = left + (right - left) / 2;
int midSquare = mid * mid;
int midOneSquare = (mid + 1) * (mid + 1);
if (x > midOneSquare) {
return findMinSquareRoot(x, mid + 1, right);
} else if (x < midSquare) {
return findMinSquareRoot(x, left + 1, mid);
} else {
return mid;
}
}
public static void main(String... args) throws Exception {
for (int i = 1; i <= 100; i++) {
int result = new ClosestPerfectSquare().getClosestPerfectSquare(i);
System.out.println(String.format("%3d : %3d : %3d", i, result, (result - i)));
}
}
}
Wednesday, 8 October 2014
Given a number, find the nearest perfect square
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment