Created
March 20, 2019 22:11
-
-
Save vijayparashar12/168376a43c31c224c8f2b937362d1005 to your computer and use it in GitHub Desktop.
Find the smallest perfect square root of a given range.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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