
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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.
- Related Articles
- Nearest prime less than given number n C++
- Smallest prime number just greater than the specified number in JavaScript
- Largest even digit number not greater than N in C++
- Largest number less than N with digit sum greater than the digit sum of N in C++
- Number of nodes greater than a given value in n-ary tree in C++
- Count pairs with sum as a prime number and less than n in C++
- Next greater Number than N with the same quantity of digits A and B in C++
- Primitive root of a prime number n modulo n in C++
- Number of elements greater than modified mean in matrix in C++
- Power of a prime number r in n! in C++
- Print all prime numbers less than or equal to N in C++
- Find the Next perfect square greater than a given number in C++
- Count number of substrings with numeric value greater than X in C++
- Finding the power of prime number p in n! in C++
- Print all Semi-Prime Numbers less than or equal to N in C++

Advertisements