In this tutorial, we are going to write a program that finds the k-th prime number which is greater than the given number n.
Let's see the code.
#include <bits/stdc++.h> using namespace std; const int MAX_SIZE = 1e6; bool prime[MAX_SIZE + 1]; void findAllPrimes() { memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= MAX_SIZE; p++) { if (prime[p]) { for (int i = p * p; i <= MAX_SIZE; i += p) { prime[i] = false; } } } } int findKthPrimeGreaterThanN(int n, int k) { for (int i = n + 1; i < MAX_SIZE; i++) { if (prime[i]) { k--; } if (k == 0) { return i; } } return -1; } int main() { findAllPrimes(); int n = 5, k = 23; cout << findKthPrimeGreaterThanN(n, k) << endl; return 0; }
If you run the above code, then you will get the following result.
101
If you have any queries in the tutorial, mention them in the comment section.