Answer:
The c++ program to check prime numbers is shown below.
#include <iostream>
using namespace std;
int main() {
int num, prime=0;
do
{
cout<<"Enter a positive number."<<endl;
cin>>num;
if(num<1)
{
cout<<"Invalid number. Enter a positive number"<<endl;
cin>>num;
}
}while(num<1);
if(num==1 || num==2 || num==3)
cout<<num<<" is a prime number."<<endl;
else if(num%2 == 0)
cout<<num<<" is not a prime number."<<endl;
else
{
for(int k=3; k<num/2; k++)
{
if(num%k == 0)
prime++;
}
if(prime>1)
cout<<num<<" is not a prime number."<<endl;
else
cout<<num<<" is a prime number."<<endl;
}
}
OUTPUT
Enter a positive number.
-7
Invalid number. Enter a positive number
0
Enter a positive number.
79
79 is a prime number.
Explanation:
The user input is validated for positivity. A do while loop along with an if statement is implemented for verification.
do
{
cout<<"Enter a positive number."<<endl;
cin>>num;
if(num<1)
{
cout<<"Invalid number. Enter a positive number"<<endl;
cin>>num;
}
}while(num<1);
The test for prime number is done by using multiple if else statements.
If user inputs 1, 2, or 3, message is displayed.
Else If user inputs an even number, message is displayed for not prime. This is done by taking modulo of the number upon division by 2.
Else if user inputs neither an even number nor a number less than 3, the modulus of the number is taken with divisors beginning from 3 up to half of the input number.
For this, an integer variable prime is initialized to 0. A number can be completely divisible by itself or by its factors.
If the number is divisible by any of the divisors, value of variable prime is increased by 1. If value of prime is greater than 1, this means that the user input is divisible by more than one divisor. Hence, the given number is not a prime number.