我该如何高效地找到一个给定的整数
n
之前的最大平方数(即4、9、16等)?我尝试了以下方法:int square = (int)Math.sqrt(number);
return square*square;
但这种方法存在明显的低效性,因为我们需要获取一个平方根然后再将其平方。
n
之前的最大平方数(即4、9、16等)?我尝试了以下方法:int square = (int)Math.sqrt(number);
return square*square;
但这种方法存在明显的低效性,因为我们需要获取一个平方根然后再将其平方。
注意:能够使用机器指令执行sqrt运算的处理器将足够快。毫无疑问,它的(微)程序采用了牛顿-拉弗森算法,这个算法具有二次收敛性,每次迭代都会使准确数字的数量翻倍。
因此,像这样的想法并不值得追求,尽管它们使用了平方等良好的特性。(请参见下一个提案)
// 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;
}
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
i * i < n
作为您的循环终止条件,而不是i < precalculated_square_root
。否则,在现代硬件上,浮点平方根可能是您能获得的最快速度。 - rici