Project Euler #7: 10001st prime

  • + 0 comments

    include

    include

    include

    using namespace std;

    vector sieve_of_eratosthenes(int max_n){ vector is_prime(max_n+1, true); vectorprimes;

    is_prime[0] = is_prime[1] = false;
    for(int p = 2; p*p <= max_n; p++){
        if(is_prime[p]){
            for(int i = p*p; i <= max_n; i+=p){
                is_prime[i] = false;
            }
        }
    }
    for(int p = 2; p <= max_n; ++p){
        if(is_prime[p]){
            primes.push_back(p);
        }
    }
    return primes;
    

    }

    int nth_prime(int n, const vector&primes){ return primes[n-1]; }

    int main(){ int T; cin >> T;

    vector<int> test_cases(T);
    int max_n = 0;
    for(int i = 0; i < T; i++){
        cin >> test_cases[i];
        max_n = max(max_n, test_cases[i]);
    }
    
    int upper_bound;
    if (max_n < 6) {
        upper_bound = 15;
    } else {
        upper_bound = static_cast<int>(max_n * (log(max_n) + log(log(max_n))));
    }
    
    vector<int> primes = sieve_of_eratosthenes(upper_bound);
    for(int N : test_cases){
        cout << nth_prime(N, primes) << endl;
    }
    
    return 0;
    

    }