JD question 1040: Prime Number (screening method for Prime Number)

Source: Internet
Author: User

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 ;}
    
   
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.