【发布时间】:2014-12-16 02:15:14
【问题描述】:
以下算法如何计算完美平方。我正在尝试使用这段逻辑来计算平方根。但我不明白它是如何计算平方根的。是否有任何算法可以执行逻辑用这段代码写的?
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;
}
【问题讨论】:
-
你能分享整个代码吗?我找不到变量“二”。
-
所有提到的变量,如一,二等都是一些初始化为相应数字的全局变量
-
这可能是 Newton-Raphson 算法。但是无论你从哪里得到它,都应该记录正在使用的算法。
-
在我看来不像 Newton-Raphson。
-
@poseidon_rishi 您正在寻找的算法,它做同样的事情是 [for i from 1 to infinity do if(i^2 == squareRoot) true; else if (i^2 > squareRoot) false;] 但是你发布的更快
标签: java algorithm square-root