在查找c ++范围内的完美正方形时由于超时错误而终止

问题描述 投票:-2回答:1

我正在尝试解决Hackerrank (link)中的Sherlock和Square问题,以便在一系列数据中找到完美的正方形。已经通过了4个测试用例但是我收到了大数的超时错误。请提出改进​​其性能的建议

我的代码如下:

#include<iostream>
#include<cmath>

using namespace std;

int squares(int a, int b) {
    long double i;
    long long int count=0;
    for(i=a;i<=b;i++)
    {
        long double b = sqrt(i);
        if(fmod(b,1)==0.000000)
        {
            count++;
        }
    }
    return count;
}

int main()
{
    int q,i,a,b;
    cin>>q;
    for(i=0;i<q;i++)
    {
        cin>>a>>b;
        int result = squares(a, b);
        cout<<result<<"\n";
    }
}
c++ c++11
1个回答
0
投票

您的速度问题是可见的,超过16秒运行,对于大输入,例如

1
1 1000000000

因此,简单的解决方案是摆脱squares()中的循环,并分析计算:

int squares(int a, int b) 
{
    auto sqrt_from = a < 0 ? 0 : static_cast<int>(std::ceil(std::sqrt(a)));
    auto sqrt_to = b < 0 ? 0 : static_cast<int>(std::floor(std::sqrt(b)));
    return std::max(sqrt_to - sqrt_from + 1, 0);
}

当然,如果你在输入处阻止负值,那么一切都可以成为unsigned而你又获得了一些:

unsigned squares(unsigned a, unsigned b) 
{
    auto sqrt_from = static_cast<unsigned >(std::ceil(std::sqrt(a)));
    auto sqrt_to =   static_cast<unsigned >(std::floor(std::sqrt(b)));
    return std::max(sqrt_to - sqrt_from + 1, 0);
}
© www.soinside.com 2019 - 2024. All rights reserved.