In: Computer Science
Develop a C++ class called PrimeNumberGenerator. An object of this class will generate successive prime numbers on request. Think of the object as being similar to the digital tasbeeh counter. It has a reset button which makes the counter return to 0. There is also a button to get the next prime number. On the tasbeeh, pressing this button increments the current value of the counter. In your object, pressing this button would generate the next prime number for display. You’ll implement the reset button as a member function reset() and the other button as a function getNextPrime(). When an object is first created and the getNextPrime() function is called, it will return the first prime number, i.e., 2. Upon subsequent calls to the getNextPrime() function, the subsequent prime numbers will be returned. Define any others functions such as constructor and attributes that you need. According to Wikipedia: “a prime number is a natural number greater than 1, that has no positive divisors other than 1 and itself.”
#include<iostream>
#include<conio.h>
using namespace std;
class PrimeNumberGenerator
{
public:
int num; //variable to
store current prime
PrimeNumberGenerator()
{
num=0; //initialising
counter
}
void reset() //reset counter to
0
{
num=0;
cout << "\nCounter
reset";
}
int checkPrime(int n) //check if a number is
prime or not
{
int i;
if(n==1)
return 0;
for(i=2;i<n;i++)
{
if(n%i==0)
//if number is divisible by any number between 2 and
itself, it's not prime
return 0;
}
return 1;
}
void getNextPrime()
{
num=num+1;
while(checkPrime(num)==0)
//increment counter till a prime is
encontered
num=num+1;
cout << "\nPrime: " <<
num;
}
};
int main()
{
char ch;
cout << "Enter 1 to get next prime, 0 to reset
counter\n";
PrimeNumberGenerator pr; //creating object of
class PrimeNumberGenerator
pr.getNextPrime(); //displaying first
prime
while(1)
{
ch=getch(); //getch() takes
input a character without waiting for pressing enter
if(ch == '0') //if input is
0, reset
{
pr.reset();
pr.getNextPrime();
}
else if(ch == '1')
pr.getNextPrime();
}
}
Sample execution:
NOTE: I've created an infinite loop. If you want the program to quit for any character, say 'q', add another if block and add a break statement.
In case of any doubt drop a comment and I'll surely get back to you.
Please give a like if you're satisfied with the answer. Thank you.