0分 求调

P3383 【模板】线性筛素数

King_and_Grey @ 2024-06-15 21:04:23

\color{red}{WA} \quad\color{red}{Code:}
#include<bits/stdc++.h>
using namespace std;
#define int long long
bool isPrime[100000005];
int n,q,ans[100000005],sum = 1,l;
signed main (){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin >> n >> q;
    isPrime[1] = 1;  
    for(int i = 2;i <= n / 2;i++){ 
        if(isPrime[i] == 0) {
            ans[sum++] = i;
            for(int j = i * i;j <= n;j += i){
                isPrime[j] = 1;   
            }
        }
    }
    for(int i = 1;i <= q;i++){
        cin >> l;
        cout << ans[l] << endl;
    }
    return 0;  
}

悬关


by I_AK_CTSC @ 2024-06-15 21:16:02

@greyandking i要循环到n,不然超过n/2的质数没有存储


by I_AK_CTSC @ 2024-06-15 21:16:49

@greyandking look

if(isPrime[i] == 0) {
            ans[sum++] = i;
            for(int j = i * i;j <= n;j += i){
                isPrime[j] = 1;   
            }
        }

要循环到 n ,否则进不了这个if,ans就没法存储到超过 n/2 的质数亲……


by hard_learn @ 2024-06-15 21:17:13

@greyandking 你的筛法有问题,不是从2到n/2,而是2到n,改一下就AC了。

AC记录


by I_AK_CTSC @ 2024-06-15 21:18:37

@ChenJiaMing110122 互关一下


by King_and_Grey @ 2024-06-15 21:19:04

谢谢各位巨佬们!!!

@ChenJiaMing110122

@I_AK_CTSC

已关注


by hard_learn @ 2024-06-15 21:19:11

@I_AK_CTSC 好


by I_AK_CTSC @ 2024-06-15 21:19:58

@ChenJiaMing110122 @greyandking thx


by guoguokao @ 2024-08-07 11:59:10

@King_and_Grey 把for循环里的n/2改n试试


|