In: Computer Science
Write a complete C++ program that at least consists of the main() function and at least two recursive functions. The first function has no return value and can be named printPrime(). It prints first n prime numbers with proper prompt. Note that number 1 is not regarded as a prime number. We assume the first prime number is 2. The printout should start from 2. The prototype of the recursive function should be
void printPrime(int n);
The algorithm of printPrime() should be using a for loop and inside the loop calling another recursive function getPrime(), which returns the nth prime number. Again we assume the first prime number, i.e. getPrime(1), is 2. The function getPrime() has following prototype.
int getPrime(int n);
getPrime() can be implemented by first calling getPrime(n-1) to get the n-1th prime number then using a while loop to find the nth prime number.
The main() function reads a positive integer with proper prompt. Then it calls the printPrime(). You can add other functions if needed.
Code:
#include<iostream>
using namespace std;
void printprime(int n);
int getprime(int n);
int s=1;
int main(){
int n;
cout<<"Enter value of n:";
cin>>n;
cout<<"prime numbers are:"<<endl;
printprime(n);
}
void printprime(int n){
if(s<=n){
cout<<(getprime(s))<<endl;
s++;
printprime(n);
}
}
int getprime(int n){
int i=2,j=2,c=0,k=0;
if(n==0){
return 0;
}
else{
if(k<=n){
while(1){
j=2;
c=0;
while(j<i){
if(i%j==0){
c=1;
}
j++;
}
if(c==0){
k++;
}
if(k==n){
break;
}
i++;
}
getprime(n-1);
return
i;
}
}
}
Output: