题意:
输入一个数字N(N <= 200000),输出底N个素数.
思路:
1-3000000中大约有210000素数.直接把这些素数打表,然后离线查询就OK.
代码:
1 #include <iostream> 2 #include <cmath> 3 #include <cstdio> 4 #include <cstring> 5 #include <cstdlib> 6 #include <algorithm> 7 #include <queue> 8 #include <stack> 9 #include <vector> 10 using namespace std; 11 typedef long long LL; 12 13 bool visit[3010000 + 7]; 14 int prime[3000000 + 7]; 15 int ans[220000 + 7]; 16 void init_prim(){ 17 memset(visit, true, sizeof(visit)); 18 int num = 0; 19 for (int i = 2; i <= 3000000; ++i){ 20 if (visit[i] == true){ 21 num++; 22 prime[num] = i; 23 } 24 for (int j = 1; ((j <= num) && (i * prime[j] <= 3000000)); ++j){ 25 visit[i * prime[j]] = false; 26 if (i % prime[j] == 0) break; 27 } 28 } 29 } 30 31 int main() 32 { 33 //freopen("input.txt", "r", stdin); 34 memset(prime, 0, sizeof(prime)); 35 init_prim(); 36 int cnt = 0; 37 for(int i = 0; i <= 3000000; i++){ 38 if(prime[i])ans[cnt++] = prime[i]; 39 } 40 int t; 41 scanf("%d", &t); 42 while(t--){ 43 int n; 44 scanf("%d", &n); 45 printf("%d\n", ans[n - 1]); 46 } 47 return 0; 48 }
时间: 2024-10-06 10:29:05