Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a C++ program which asks the user to enter a positive integer n. Your pro

ID: 3839001 • Letter: C

Question

Create a C++ program which asks the user to enter a positive integer n.

Your program will then display the nth prime number.

A prime number is a positive integer p which has exactly 2 factors, 1 and p.

For example, 13 is prime because the only factors are 1 and 13. The number 13 is the 6th prime number (after 2, 3, 5, 7, 11).

A number like 6 is not prime because it has factors 1, 2, 3, and 6.

To do this program, make a function named isPrime whose input is an integer. The function should return 0 if the integer is not prime and 1 if the integer is prime. Now to find the nth prime number, simply start a loop 2, 3, . . . and keep track of how many times isPrime returns 1.

Explanation / Answer

Program : (explanation included as coments)

#include <iostream>

using namespace std;

bool isPrime(int num);

void main(){
  
   cout << "Enter any positive integer ";
   int number;
   cin >> number ;

   int count =0 ;
   int tempNum=2;

   //start an inifinte loop , whenever we come across nth prime number ...break loop
   while(true){
       //if we ind any prime number increment the loop
       if(isPrime(tempNum)){
           count++;
       }

       //if value of count is equal to entered number then break the loop
       if(count==number){
           break;
       }
       tempNum++;
   }

   cout <<"Answer is " << tempNum;
}

bool isPrime(int num){

   int count = 0;

   //loop to find the number of factors between 2 and half of the number because no factor other than itself
   //will be grater than half of the number
   for(int i = 2 ; i <=num/2 ; i++){
       //if we find atleast one factor return false
       if(num%i==0){
           return false;      
       }
      
   }
   //if no factor is found return true
   return true;
}

output:

Enter any positive integer

5

Result is 11