【问题标题】:Find Number Of Square Roots Between Two Numbers求两个数之间的平方根数
【发布时间】:2016-04-15 19:10:22
【问题描述】:

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

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;
}

这会很好,但我在考虑它的性能。 因为在这种情况下,inner For loop 将从起始位置 (1) 开始执行,因此如果有人将较大的数字范围传递给该方法,将需要一些时间。

所以,我的问题是:

有没有其他方法可以找到更好的性能?

P.S.- 我不能使用Math.sqrt() 函数

【问题讨论】:

  • 你的函数只适用于完美平方根?
  • 您可以绕过规则并实施Newton's Method 来计算平方根...但这可能不是您想要的:P
  • 我希望如此,它适用于我测试过的少数案例。有什么问题再帮我看看吧。
  • SamYounnou 有个好主意
  • y * y &lt;= no2 为假时,你也可以打破你的内循环

标签: java performance for-loop


【解决方案1】:
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;
}

【讨论】:

    【解决方案2】:

    你可以通过摆脱外部循环来摆脱单个 for 循环

    static int findRoot(int lo, int hi) {
        int numRoots = 0;
    
        for (int x = 0, x2 = 0; x2 <= hi; x++, x2 = x * x) {
            if (x2 >= lo) {
                numRoots++;
            }
        }    
    
        return numRoots;
    }
    

    在这里,您实际上只需执行一次内部循环,当x2(x 平方)在lohi 之间时递增numRoots,并在x2 大于hi 时终止循环(而不是当x 大于hi 时就像您的代码一样)。

    【讨论】:

    • 您错过了将零作为可能的平方根。以“x=0, x2=0”开头。
    【解决方案3】:

    它也会起作用。

    static int FindRoot2(int no1, int no2) {
        int res = 0;
        int inner=1;
        for (int x = no1; x <= no2; x++) {
            for (int y = inner; y <= no2; y++) {
                if (y * y == x)
                {
                    inner=y;
                    res++;
                }
            }
        }
        return res;
    }
    

    在这种情况下,内部循环不会从 1 开始执行。

    【讨论】:

    • 这确实做了一些优化,但没有理由使用除了清晰、直接的 O(n) 解决方案之外的解决方案。
    【解决方案4】:

    您当前的算法效率低下的原因有很多,但最大的一个原因是内部 for 循环不是必需的。

    您正在寻找的算法背后的想法是,从高于或等于 no1 的最低完美方格开始,然后进入下一个完美方格,然后再下一个,跟踪您击中了多少个, 直到你所在的完美方格高于 no2。

    static int FindRoot(int no1, int no2) {
    
        int res = 0;
        int x = 1;
    
        // This loop gets x to the first perfect square greater than
        // or equal to no1
        while( (x * x) < no1 ) {
            x++;
        }
    
        // This loop adds 1 to res and increases x
        // as long as x^2 is less than or equal to no2
        for(; (x * x) <= no2; x++, res++) { }
    
        return res;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多