由于 Hackerrank 中的超时而终止(在 cpp 中使用 malloc)

Terminated due to timeout in Hackerrank (using malloc in cpp)

所以我是一个非常新的程序员,我刚刚开始在 Hackerrank 上做题。我尝试了一个问题,它编译并离线工作 ide。但在 hackerrank 上显示错误。及时的回答对我很有帮助。

这是素数螺旋的虚拟表示(用于理解目的)

现在的问题 素数以螺旋形式书写,从原点 (0, 0) 开始,并如上图所示移动。右栏和底行显示的数字分别是列号和行号(即y和x坐标)

objective是求给定素数的位置(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);

    }
}

你的问题是这个循环:

for (int i = 2; i <= 12000000; i++)
...
    for (int j = 2; j <= i; j++)
    ...

您最终将按照内部循环的 n^2 次迭代的顺序进行操作,其中 n=12000000,因此您的内部循环有 144*10^12 次迭代。

让我们假设每次迭代需要 1 纳秒(实际上会长很多),因此调用 [=11= 需要 144*10^12 / 10^9 = 144000 秒,或约 1.7 天] 完成,除非你在 if (a == i).

上中断

因此,如果您的测试用例碰巧调用了 prime 并且 a,很可能会超出分配的时间预算。