全RE求助!

P3383 【模板】线性筛素数

zjinyi @ 2025-01-11 18:47:02

我的代码:

#include <iostream>
using namespace std;

bool vis[100000000];
int prime[50000000];

void init(int maxn)
{
    int cnt = 0;
    for (int i = 2; i < maxn; ++i)
    {
        if (vis[i] == false)
        {
            prime[cnt] = i;
            cnt += 1;
        }
        for (int j = 1; j <= cnt && i * prime[j] < maxn; ++j)
        {
            vis[prime[j] * i] = 1;
            if (i % prime[j] == 0)
            {
                break;
            }
        }
    }
}

int main()
{
    std::ios::sync_with_stdio(0);
    int n, q;
    cin >> n >> q;
    init(n);
    int a;
    cout << prime[1] << " " << prime[2] << " " << prime[3];
    for (int i = 0; i < q; ++i)
    {
        cin >> a;
        cout << prime[a] << endl;
    }

    return 0;
}

似乎不是因为数组开大了


by jimmy0926 @ 2025-01-12 14:56:16

@zjinyi

#include <iostream>
using namespace std;

bool vis[100000000];
int prime[50000000];

void init(int maxn)
{
    int cnt = 1;                                                       //原本是0
    for (int i = 2; i <= maxn; ++i)                                    //原本是<
    {
        if (vis[i] == false)
        {
            prime[cnt] = i;
            cnt += 1;
        }
        for (int j = 1; j <= cnt && i * prime[j] <= maxn; ++j)           //原本是<
        {
            vis[prime[j] * i] = 1;
            if (i % prime[j] == 0)
            {
                break;
            }
        }
    }
}

int main()
{
    std::ios::sync_with_stdio(0);
    int n, q;
    cin >> n >> q;
    init(n);
    int a;
    for (int i = 0; i < q; ++i)
    {
        cin >> a;
        cout << prime[a] << endl;
    }

    return 0;
}

by zjinyi @ 2025-01-12 15:39:45

@jimmy0926 变成了全 WA

#include <iostream>
using namespace std;

bool vis[100000000];
int prime[50000000];

void init(int maxn)
{
    int cnt = 1;
    for (int i = 2; i <= maxn; ++i)
    {
        if (vis[i] == false)
        {
            prime[cnt] = i;
            cnt += 1;
        }
        for (int j = 1; j <= cnt && i * prime[j] <= maxn; ++j)
        {
            vis[prime[j] * i] = 1;
            if (i % prime[j] == 0)
            {
                break;
            }
        }
    }
}

int main()
{
    std::ios::sync_with_stdio(0);
    int n, q;
    cin >> n >> q;
    init(n);
    int a;
    cout << prime[1] << " " << prime[2] << " " << prime[3];
    for (int i = 0; i < q; ++i)
    {
        cin >> a;
        cout << prime[a] << endl;
    }

    return 0;
}

by CatnipQwQ @ 2025-01-12 16:37:20

@zjinyi 题目好像没要求输出前 3 个质数吧,把第 35 行去掉就可以了 qwq。


by zjinyi @ 2025-01-12 18:49:00

@CatnipQwQ 似乎是的,我真聪明,去掉调代码用的 35 行就过了


|