OJ question: click here ~~
Question Analysis: output the k-th prime number
The purpose of posting such a simple question is not pure
The basic idea of using the sieve method to calculate the prime number is to arrange the positive integers in a certain range from 1 in ascending order. 1 is not a prime number, and it is first screened out. In the remaining number, select the smallest number as the prime number, and then remove its multiples. And so on until the sieve is empty. For example:
1 2 3 4 5 6 7 8 9 1011 12 13 14 15 16 17 18 19 2021 22 23 24 25 26 27 28 29 301 is not a prime number, remove it. 2 is the smallest of the remaining number, which is the prime number. Remove the multiple of 2. The remaining number is: 3 5 7 9 11 13 15 17 19 21 23 25 27 29 the remaining number is the smallest of 3, is a prime number, remove the multiple of 3, so that until all the numbers are filtered out, the obtained prime number is: 2 3 5 7 11 13 17 19 23 29
AC_CODE
#include
#include
#include
#include
using namespace std ;const int N = 1000000;bool prime[N] ;void initprime(){ memset(prime, 1 , sizeof(prime)) ; prime[0] = prime[1] = 0 ; double t = sqrt(N) + 1 ; for(int i = 2;i < t;i++){ if(prime[i]){ for(int j = i + i;j < N;j += i) prime[j] = false ; } }}int main(){ initprime(); int k , t ; while(cin >> k){ t = 0 ; for(int i = 0;i < N;i++){ if(prime[i]){ t++; if(t == k){ cout << i << endl ; break ; } } } } return 0 ;}