java - 求两个数之间的平方根

标签 java performance for-loop

我编写了这个函数来查找两个数字(包括)之间的平方根。

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/

相关文章:

Java可以在新行准确时将一个字符串分成2个字符串吗

java - SWT 可编辑组合 - 突出显示文本

java - 如何在Eclipse IDE中的Apache Tomcat服务器中部署创建的.jar文件?

c++ - 在 C/C++ 中包含未使用的头文件是否会影响性能?

c - 这个迭代如何工作 : for(++s ; *s;++s)

c - 最后通过一个循环,在函数调用时表现出奇怪和隐含的错误?

javascript - 等待循环完成后再执行下一个操作

java - 根据条件如何创建 StringBuffer 并向其中追加数据

c# - Entity Framework 缓慢的第一次调用IRepository DbContext

performance - MongoDB动态排名