簡體   English   中英

找到小於n的最大平方數的算法

[英]Algorithm to find the largest square number smaller than n

我怎樣才能找到最大的平方數(即4,9,16)比定int小n有效? 我有以下嘗試:

int square = (int)Math.sqrt(number);
return square*square;

但它有一個明顯的低效率,即獲得一個平方根,這樣我們就可以解決它。

預先:應該注意的是,能夠將sqrt作為機器指令的處理器將足夠快。 毫無疑問,它的(微)程序使用Newton-Raphson,並且該算法具有二次收斂性,每次迭代時精確數字的數量加倍。

所以,像這樣的想法並不值得追求,盡管它們使用了正方形等不錯的屬性(參見下一個提案)

// compute the root of the biggests square that is a power of two < n
public static int pcomp( int n ){
  long p2 = 1;
  int i = 0;
  while( p2 < n ){
    p2 <<= 2;
    i += 2;
  }
  p2 >>= 2;
  i -= 2;
  return (int)(p2 >>= i/2);
}

public static int squareLowerThan( int n ){
  int p = pcomp(n);
  int p2 = p*p;     // biggest power of two that is a square < n 
  int d = 1;        // increase using odd numbers until n is exceeded
  while( p2 + 2*p + d < n ){
    p2 += 2*p + d;
    d += 2;
  }
  return p2;
}

但我確信牛頓的算法更快。 二次收斂,記住。

public static int sqrt( int n ){
  int x = n;
  while( true ){
    int y = (x + n/x)/2;
    if( y >= x ) return x;
    x = y;
  }
}

這將返回整數平方根。 返回x * x以獲得n下方的平方。

線性時間算法:

int largestSquare(int n) {
  int i = 0;
  while ((i+1)*(i+1) < n) {
    ++i;
  }
  return i*i;
}

有一個牛頓算法可以找到平方根,在給定的鏈接中你需要的是m ^ 2而不是m

https://math.stackexchange.com/questions/34235/algorithm-for-computing-square-root-of-a-perfect-square-integer

即使你想直接找到方形而不是找到m,我也不認為它比這更快。

並在這里工作代碼

public static int squareLessThanN(int N)
{
        int x=N;
        int y=(x+N/x)/2;
        while(y<x)
        {
               x=y;
               y=(x+N/x)/2;
        }
        return x*x;
 }

但似乎內置的平方根似乎更快。 剛剛測量了兩者的運行時間。

class Square{
        public static void main(String[] args)
        {
                long startTime = System.currentTimeMillis();
                System.out.println(squareLessThanN(149899437943L));
                long endTime   = System.currentTimeMillis();
                long totalTime = endTime - startTime;
                System.out.println("Running time is "+totalTime);

                startTime = System.currentTimeMillis();
                System.out.println(normal(149899437943L));
                endTime   = System.currentTimeMillis();
                totalTime = endTime - startTime;
                System.out.println("Running time is "+totalTime);

        }
        public static long squareLessThanN(long N)
        {
                long x=N;
                long y=(x+N/x)/2;
                while(y<x)
                {
                        x=y;
                        y=(x+N/x)/2;
                }
                return x*x;
        }
        public static long normal(long N)
        {
                long square = (long)Math.sqrt(N);
                return square*square;
        }
}

輸出是

149899060224
Running time is 1
149899060224
Running time is 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM