Java examples for java.lang:Math Algorithm
is Perfect Square
//package com.java2s; import java.math.BigDecimal; import java.math.RoundingMode; public class Main { private static BigDecimal zero = BigDecimal.valueOf(0); private static BigDecimal one = BigDecimal.valueOf(1); private static BigDecimal two = BigDecimal.valueOf(2); public static boolean isPerfectSquare(BigDecimal num) { BigDecimal low = zero;/* ww w. ja v a 2 s . c o m*/ BigDecimal high = num; while (low.compareTo(high) <= 0) { BigDecimal mid = low.add(high).divide(two) .setScale(0, RoundingMode.DOWN); BigDecimal square = mid.multiply(mid); int comparison = square.compareTo(num); if (comparison == 0) { return true; } else if (comparison > 0) { high = mid.subtract(one); } else { low = mid.add(one); } } return false; } }