C++ program to find nth prime number

In this example, you will take a number from the user and find the nth prime number in the C++ program.

The number which will divide by 1 or itself is called a prime number except 1, for example, 2, 3, 5, 7, etc are prime numbers.

input: 5
output: 11 

For example, if the user enters 5 then the 5th prime number is 11.

Find Nth prime number program in C++


#include<iostream>
using namespace std;
int main()
{
    int num,PrimeCount=0,i,flag,prime=1;
    cout << "enter the number:";
    cin >> num;
    while(num!=PrimeCount)
    {
        flag=0;
        prime++;
        for(i=2;i<=(prime/2);i++)
        {
            if(prime%i==0)
                flag=1;
        }
        
        if(flag==0)
        {
            PrimeCount++;
        }
    }
     cout << num << "th prime number is:"<<prime;
    return 0;
}
output
enter the number:6
6th prime number is:13

Logic to find nth prime number in C++

Take a number from the user and stored it in variable num.

Iterate loop until PrimeCount is equal to num.

Inside the outer loop, iterate the inner loop from 2 to prime/2. (inner loop find the prime number)

inside the inner loop, check if the remainder is zero i.e prime%i==0, then set the flag=1. (flag=1 means the number is not prime).

In the outer loop, use the if-statement to check flag value is zero i.e flag==0, if the flag value is zero then the number is prime, inside the if-statement increment value of PrimeCount.


Find The Nth prime number in C++ using function


#include<iostream>
using namespace std;

int FindNthPrime(int num);
int main() {
  int num, prime = 1;
  cout << "enter the number:";
  cin >> num;
  prime = FindNthPrime(num);
  cout << num << "th prime number is:" << prime;
  return 0;
}

int FindNthPrime(int num) {
  int PrimeCount = 0, i, flag, prime = 1;
  while (num != PrimeCount)
  {
    flag = 0;
    prime++;
    for (i = 2; i <= (prime / 2); i++)
    {
      if (prime % i == 0)
        flag = 1;
    }

    if (flag == 0) {
      PrimeCount++;
    }
  }
  return prime;
}
output
enter the number:5
5th prime number is:11