洛谷:P3383 【模板】线性筛素数

【模板】线性筛素数

题目背景

本题已更新,从判断素数改为了查询第 k k k 小的素数
提示:如果你使用 cin 来读入,建议使用 std::ios::sync_with_stdio(0) 来加速。

题目描述

如题,给定一个范围 n n n,有 q q q 个询问,每次输出第 k k k 小的素数。

输入格式

第一行包含两个正整数 n , q n,q n,q,分别表示查询的范围和查询的个数。

接下来 q q q 行每行一个正整数 k k k,表示查询第 k k k 小的素数。

输出格式

输出 q q q 行,每行一个正整数表示答案。

样例 #1

样例输入 #1

100 5
1
2
3
4
5

样例输出 #1

2
3
5
7
11

提示

【数据范围】
对于 100 % 100\% 100% 的数据, n = 1 0 8 n = 10^8 n=108 1 ≤ q ≤ 1 0 6 1 \le q \le 10^6 1q106,保证查询的素数不大于 n n n

Data by NaCly_Fish.

线性筛素数模板,不熟可以多加练习

#include <bits/stdc++.h>
// #include<iostream>
// #include<iomanip>
// #include<vector>
// #include<queue>
// #include<cstring>
// #include <algorithm>
// #define int long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
using namespace std;

#define endl '\n'
const int M = 1e7 + 7;
const int N = 1e8 + 7;

int primes[M],cnt=0;
bool st[N];
void getprime(int n)
{
  for(int i=2;i<=n;i++)
  {
    if(!st[i])
    {
         primes[cnt++]=i;
    }
    for(int j=0;primes[j]<=n/i;j++)
    {
      st[primes[j]*i]=1;
      if(i%primes[j]==0)break;
    }
  }

}

int main()
{
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
 int n,t;
cin>>n>>t;
 getprime(n);
   while(t--)
   {
    int m;
    cin>>m;
   cout<<primes[m-1]<<endl;
   }
  return 0;
}

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值