Merge pull request #10271 from abdallahsawan/BAEL-4696

Bael 4696
This commit is contained in:
bfontana 2020-11-29 01:01:16 -03:00 committed by GitHub
commit c88f1c7a28
2 changed files with 76 additions and 0 deletions

View File

@ -0,0 +1,49 @@
package com.baeldung.perfectsquare;
public class PerfectSquareUtil {
public static boolean isPerfectSquareByUsingSqrt(long n) {
if (n <= 0)
return false;
double perfectSquare = Math.sqrt(n);
long tst = (long)(perfectSquare + 0.5);
return tst*tst == n;
}
public static boolean isPerfectSquareByUsingBinarySearch(long low, long high, long number) {
long check = (low + high) / 2L;
if (high < low)
return false;
if (number == check * check) {
return true;
} else if (number < check * check) {
high = check - 1L;
return isPerfectSquareByUsingBinarySearch(low, high, number);
} else {
low = check + 1L;
return isPerfectSquareByUsingBinarySearch(low, high, number);
}
}
public static boolean isPerfectSquareByUsingNewtonMethod(long n) {
long x1 = n;
long x2 = 1L;
while (x1 > x2) {
x1 = (x1 + x2) / 2L;
x2 = n / x1;
}
return x1 == x2 && n % x1 == 0L;
}
public static boolean isPerfectSquareWithOptimization(long n) {
if (n < 0)
return false;
switch ((int) (n & 0xF)) {
case 0: case 1: case 4: case 9:
long tst = (long) Math.sqrt(n);
return tst * tst == n;
default:
return false;
}
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.perfectsquare;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PerfectSquareUnitTest {
@Test
public void test0xFFAssignedToInteger() {
long n = 18676209273604L; // 18676209273604 = 43621598 * 43621598
boolean expectedValue = true;
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingSqrt(n));
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingBinarySearch(1, Integer.MAX_VALUE, n));
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingNewtonMethod(n));
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareWithOptimization(n));
}
@Test
public void test0xFFAssignedToByte() {
long n = 549790047707L; // prime number
boolean expectedValue = false;
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingSqrt(n));
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingBinarySearch(1, Integer.MAX_VALUE, n));
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingNewtonMethod(n));
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareWithOptimization(n));
}
}