Fastest way to determine if an integer's square root is an integer

前端 未结 30 2104
心在旅途
心在旅途 2020-11-22 02:17

I\'m looking for the fastest way to determine if a long value is a perfect square (i.e. its square root is another integer):

  1. I\'ve done it the ea
30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 02:39

    Newton's Method with integer arithmetic

    If you wish to avoid non-integer operations you could use the method below. It basically uses Newton's Method modified for integer arithmetic.

    /**
     * Test if the given number is a perfect square.
     * @param n Must be greater than 0 and less
     *    than Long.MAX_VALUE.
     * @return true if n is a perfect
     *    square, or false otherwise.
     */
    public static boolean isSquare(long n)
    {
        long x1 = n;
        long x2 = 1L;
    
        while (x1 > x2)
        {
            x1 = (x1 + x2) / 2L;
            x2 = n / x1;
        }
    
        return x1 == x2 && n % x1 == 0L;
    }
    

    This implementation can not compete with solutions that use Math.sqrt. However, its performance can be improved by using the filtering mechanisms described in some of the other posts.

提交回复
热议问题