Skip to content

Instantly share code, notes, and snippets.

@vijayparashar12
Created March 20, 2019 22:11
Show Gist options
  • Save vijayparashar12/168376a43c31c224c8f2b937362d1005 to your computer and use it in GitHub Desktop.
Save vijayparashar12/168376a43c31c224c8f2b937362d1005 to your computer and use it in GitHub Desktop.
Find the smallest perfect square root of a given range.
public static class Solution {
public static void main(String[] args) {
int a = 6000, b = 7000;
// int a = 10, b = 20;
// int a = 8, b = 24;
int smallestPerfect = getSmallestPerfectSqrt(a, b);
System.out.println(stepsToSmallestSqrt(smallestPerfect));
}
private static int getSmallestPerfectSqrt(int a, int b) {
int smallestPerfect = a;
for (int i = a; i < b; i++) {
final double sqrt = Math.sqrt(i);
int intPart = (int) sqrt;
double d = sqrt - intPart;
if (d == 0) {
smallestPerfect = i;
break;
}
}
return smallestPerfect;
}
private static int stepsToSmallestSqrt(int a) {
if (a == 2 || a == 3) {
return 0;
} else {
final int sqrt = (int) Math.sqrt(a);
System.out.println(sqrt);
return 1 + stepsToSmallestSqrt(sqrt);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment