Problem 7 : 10001st prime

Problem 7


10001st prime

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?


10001st prime number

List the first 6 prime numbers, which are 2, 3, 5, 7, 11, and 13. We can see that the sixth prime number is 13.

What is the 10,001st prime number?


Naive solution: violent enumeration (enumeration determines whether each number is a prime number, and then the counter counts, the prime number theorem needs to be used here)

    Prime number theorem:

                    

    The result obtained by the function approaches the number of prime numbers below x. In this regard, we can roughly estimate a previous

Optimization algorithm: In this question, we use a linear sieve method to filter prime numbers. The time complexity of a linear sieve is O(N).

Linear Sieve

    First we need to consider why the time complexity of a linear sieve is O(N) while the time complexity of a prime sieve is O(logN).

    For the number 30, if we use the prime number sieve, he is a multiple of 2, a multiple of 3, and a multiple of 5, and he is marked 3 times in total. And if we use a linear sieve, we only need to mark it once.

    The idea of ​​linear sieve: If the prime number sieve is to use the prime number to mark the composite number, then the linear sieve is to use the composite number to mark the composite number. Suppose we traverse the number that has reached n, then the numbers less than n have been filtered out, then we need to traverse from the first prime number, multiply n by the number of this prime number to mark, until the smallest prime factor of n End of tag.


topic code

#include <stdio.h>
#include <math.h>
#include <inttypes.h>
#define N 200000
int32_t prime[N];
void getprime(){
    for (int32_t i = 2;i < N;i++){
        if(!prime[i])prime[++prime[0]] = i;
        for(int32_t j=1;j<=prime[0];j++){
            if(i * prime[j] > N)break;
            prime[i*prime[j]] = 1;
            if(i % prime[j] == 0)break;
        }
    }
}
int32_t main(){
    getprime();
    printf("%" PRId32 "\n",prime[10001]);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326833086&siteId=291194637