【发布时间】:2020-04-27 21:38:32
【问题描述】:
所以我是一个相当新的程序员,我刚刚开始在 Hackerrank 上做问题。我尝试了一个问题,它可以在离线 ide 上编译和工作。但是在hackerrank上显示错误。及时的回答对我很有帮助。
这是素数螺旋的虚拟表示(用于理解目的)
现在的问题 质数以螺旋形式书写,从原点 (0, 0) 开始,如上图所示移动。右列和底行显示的数字分别是列号和行号(即y和x坐标)
目标是找到给定素数的位置(x 和 y 坐标)。
错误 当我在hackerrank中运行代码时,3个测试用例中有2个有效。但是对于一个测试用例,它显示错误因超时而终止。 我写的代码如下:
#include<iostream>
using namespace std;
int prime(int a)
{
int count, h=0;
for (int i = 2; i <= 12000000; i++)
{
count = 0;
for (int j = 2; j <= i; j++)
{
if(i%j==0)
{
count++;
}
}
if (count == 1)
{
h = h + 1;
}
if (a == i)
{
break;
}
}
return h;
}
void spiral(int h)
{
int stepnum=1, totalsteps = 2;
int x_coordinate = 0, y_coordinate = 0;
int operatn = 1;
for(int i=2;i<=h;i++)
{
if (stepnum <= (totalsteps/2))
{
x_coordinate = x_coordinate + operatn;
}
else
{
if (stepnum <= totalsteps)
{
y_coordinate = y_coordinate + operatn;
}
}
if (stepnum == totalsteps)
{
stepnum = 0;
operatn = -1 * operatn;
totalsteps = totalsteps + 2;
}
stepnum++;
}
cout << "x coordinate = "<<x_coordinate<< " y coordinate = "<<y_coordinate<<endl;
}
int main()
{
int t;
int* p;
cout<<"Enter the number of cases :"<< endl;
cin >> t;
int test;
p=(int*)malloc(t*4);
for (int i = 0; i < t; i++)
{
cin >> *(p+i);
}
for (int i = 0; i < t; i++)
{
test = prime(*(p + i));
spiral(test);
}
}
【问题讨论】:
-
p=(int*)malloc(t*4);使用sizeof(int)因为不能保证 int 总是 4 个字节。不过,真的,请使用new或vector。使用测试用例的限制作为指导来测试和分析您的代码。寻找最坏的情况,并确保您在时间限制之内。对于这样的问题,您通常希望找到一种方法来缓存尽可能多的数据,这样您就不会每次都计算它。 -
素数测试可以加快速度。无需将测试用例保存在数组中(我初学者时也习惯);获取输入,进行计算并将其输出到新行。测试人员将检查您的整个输出文件是否与他们的匹配。我看到函数
prime正在计算素数a的“等级”,它也可以通过计算所有素数的等级来加速(直到问题陈述中必须给出的最大值),然后再计算输入然后查找排名将只查找预先计算的数组。函数spiral也可以做类似的事情。
标签: c++ performance memory-efficient