以下算法如何计算完美正方形。我正在尝试使用这条逻辑来计算平方根。但我不明白它是如何计算平方根的。是否有任何算法可以做逻辑用这段代码写的?
public static boolean isPerfectSquare(BigDecimal num) {
BigDecimal squareRoot = one;
BigDecimal square = one;
BigDecimal i = one;
BigDecimal newSquareRoot;
int comparison = -1;
while (comparison != 0) {
if (comparison < 0) {
i = i.multiply(two);
newSquareRoot = squareRoot.add(i).setScale(0, RoundingMode.HALF_UP);
} else {
i = i.divide(two);
newSquareRoot = squareRoot.subtract(i).setScale(0, RoundingMode.HALF_UP);
}
if (newSquareRoot.compareTo(squareRoot) == 0) {
return false;
}
squareRoot = newSquareRoot;
square = squareRoot.multiply(squareRoot);
comparison = square.compareTo(num);
}
return true;
}
答案 0 :(得分:3)
我建议您添加一些System.out.println()
来电,以了解自己的进展情况。
下面是我在完成相同操作并在101上运行后收到的输出。它只是增加猜测直到它太高,然后改进它的猜测,直到它找到完全匹配或确定它不能。
它的改进过程是逐渐减小步骤,直到它太低。然后它跳回来(步骤加倍)并且它再次开始向下踩。如果它到达其步长值小于1的点,则它放弃,因为参数不是完美的正方形。如果在任何步骤中,猜测的平方与参数匹配,那么您已经找到了平方根,因此您知道参数是一个完美的正方形。
1 is lower than 101: adding 2. New guess at square root is 3 ( 9)
9 is lower than 101: adding 4. New guess at square root is 7 ( 49)
49 is lower than 101: adding 8. New guess at square root is 15 (225)
225 is higher than 101: subbing 4. New guess at square root is 11 (121)
121 is higher than 101: subbing 2. New guess at square root is 9 ( 81)
81 is lower than 101: adding 4. New guess at square root is 13 (169)
169 is higher than 101: subbing 2. New guess at square root is 11 (121)
121 is higher than 101: subbing 1. New guess at square root is 10 (100)
100 is lower than 101: adding 2. New guess at square root is 12 (144)
144 is higher than 101: subbing 1. New guess at square root is 11 (121)
121 is higher than 101: subbing 0.5. New guess at square root is 11 (121)
101 is not a perfect square