【问题标题】:How to find number of perfect squares in the given range?如何在给定范围内找到完美正方形的数量?
【发布时间】:2015-05-17 10:11:04
【问题描述】:

由于t 的大量输入超时,它给出了一个错误终止。 求给定范围内完美正方形的个数

 #include <stdio.h>
    #include <string.h>
    #include <math.h>
    #include <stdlib.h>

    int main() 
    {

        double s,e,i;
       int t;
       scanf("%d",&t);
       for (;t>0;t--)
            {
             int cnt=0;
             scanf("%lf%lf",&s,&e);
             for (i=s;i<=e;i++)
                {
                 if (sqrt(i)==ceil(sqrt(i)))
                 cnt++;
                }
            printf("%d\n",cnt);
            }
        return 0;
    }

【问题讨论】:

    标签: c algorithm math


    【解决方案1】:

    有个窍门。

    • 求下限和上限的平方根
    • 取它们不可分割的一部分,然后
    • 从上限中减去下限的整数部分。

    您还需要检查下界是否为完美正方形。如果是,则将1 添加到差异中。

    例如:1100 之间的完全平方数是 10 - 1 = 9。由于1 也是一个完美的正方形,因此添加1,因此结果将是10

    int result = (int)sqrt(upper_bound) - (int)sqrt(lower_bound);  
    if(lower_bound == (int)sqrt(lower_bound)*(int)sqrt(lower_bound))  
        result += 1;  
    

    请注意,我认为包括上限和下限。

    【讨论】:

    • +1。这是正确的做法。 “检查下界”、“检查上界”和“加1”都属于“是否包含边界”的范畴。
    【解决方案2】:

    方法2(高效)我们可以简单地取a的平方根和b的平方根,并计算它们之间的完美平方

    floor(sqrt(b)) - ceil(sqrt(a)) + 1
    

    我们选择 sqrt(b) 是因为我们需要考虑 b之前的数字

    我们取 sqrt(a) 的 ceil 因为我们需要考虑 a后的数字

    例如,设 b = 24,a = 8。 floor(sqrt(b)) = 4 ceil(sqrt(a)) = 3 方格数是 4 - 3 + 1 = 2 这两个数是 9 和 16

    【讨论】:

    • 比原答案好解释和代码精简
    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多