c++ - 由于在 C++ 范围内查找完美正方形时出现超时错误而终止
问题描述
我正在尝试解决 Hackerrank (链接)中的 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";
}
}
解决方案
对于大输入,例如运行超过 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);
}
推荐阅读
- node.js - Nodejs,没有使用 sequelize 和 Promise 链回滚
- gstreamer - Gstreamer 探测信息数据
- c++ - 包含头文件添加到特定类时会导致编译错误
- java - Apache Ignite 嵌入式集群模式
- terraform - 字符串列表的 Terraform 可选参数
- windows - 运行基于 GEANT4 的示例应用程序时出错。“指定的会话类型未在您的系统中构建,或未指定会话类型
- python - 如何降低 PySpark 中 ArrayType 或 MapType 列中元素名称的大小写?
- performance - jmeter.properties 和 jmeter-server 文件中需要什么更新来创建 JMeter 远程负载测试
- reactjs - 错误:对象作为 React 子级无效如果您打算渲染一组子级,请改用数组我不确定我哪里出错
- javascript - 使用javascript自动提交表单仍然需要交互才能完成