Computer >> Computer tutorials >  >> Programming >> C++

Kth prime number greater than N in C++


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.

  • Initialise the number n.
  • Find all the prime numbers till 1e6 and store it in a boolean array.
  • Write a loop that iterates from n + 1 to 1e6.
    • If the current number is prime, then decrement k.
    • If k is equal to zero, then return i.
  • Return -1.

Example

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

Output

If you run the above code, then you will get the following result.

101

Conclusion

If you have any queries in the tutorial, mention them in the comment section.