0分,全TLE 求优化

P3383 【模板】线性筛素数

_luogu_huowenshuo_ @ 2024-08-21 11:21:55

#include <bits/stdc++.h>
using namespace std;
int n,a[2000005],z,q,b[2000005];
bool isprime(int n)
{
    if(n==1)
        return false;
    if(n==2)
        return true;
    for(int i=2;i*i<=n;i++)
        if(n%i==0)
            return false;
    return true;
}
int main(){
    std::ios::sync_with_stdio(0);
    cin >> n >> q;
    for(int i=1;i<=n;i++)
        if(isprime(i))
            a[++z]=i;
    for(int i=1;i<=q;i++)   
        cin >> b[i];
    for(int i=1;i<=q;i++)   
        cout << a[b[i]] << endl;
    return 0;
}

by bfs_MST @ 2024-08-21 11:27:22

@huowenshuo 你会不会筛法求素数?


by King_and_Grey @ 2024-08-21 11:28:51

@huowenshuo

#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;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 _luogu_huowenshuo_ @ 2024-08-21 11:32:35

@King_and_Grey 谢谢


|