我编写了这个函数来查找两个数字(包括)之间的平方根。
static int FindRoot(int no1, int no2) {
int res = 0;
for (int x = no1; x <= no2; x++) {
for (int y = 1; y <= no2; y++) {
if (y * y == x)
res++;
}
}
return res;
}
这会很好地工作,但我正在考虑它的性能。
因为在这种情况下,内部 For 循环
将从起始位置 (1) 开始执行,因此如果有人向该方法传递较大的数字范围,则需要时间。
所以,我的问题是:
Is there any other way i can find this with better performance?
P.S.-我无法使用 Math.sqrt()
函数
最佳答案
static int FindRoot(int no1, int no2) {
int res = 0;
int x = 0;
// Ignore squares less than no1
while(x*x < no1) {
x++;
}
// Count squares up to and including no2
while(x*x <= no2) {
res++;
x++;
}
return res;
}
关于java - 求两个数之间的平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36655126/