【问题标题】:Check a number is perfect square or not检查一个数字是否完全平方
【发布时间】: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


【解决方案1】:

我建议您添加一些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

【讨论】:

  • 对于这种算法和问题解决我们该怎么说。无论如何感谢您的回答。自 2-3 天以来一直被逻辑错误。
猜你喜欢
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 2022-01-17
  • 1970-01-01
  • 2017-01-09
相关资源
最近更新 更多