In this program, you will learn about C++ program to check prime number in two different ways.
First, let’s be clear about the prime number:
A number is called prime number if it is divisible by 1 and itself only.
For example: 1, 3, 5, …., 91, ….
//C++ program to check for prime number
#include<iostream>
using namespace std;
int main()
{
int num, i, j = 0;
cout << "Enter number: ";
cin >> num;
//check for prime number
for (i = 1; i <= num; i++)
{
if ((num % i) == 0)
{
j++;
}
}
if (j == 2)
cout << "\n" << num << " is a prime number.\n";
else
cout << num << " is not a prime number.\n";
return 0;
}
Output
Explanation
The logic of the above program is to check the number entered by the user is perfectly divisible by 1 and itself which is accomplished inside for
loop.
The iteration continues till the value of i
equals the number.
Let’s check out another way of solving the same problem.
//C++ program to check for prime number
#include<iostream>
using namespace std;
int main()
{
int num, i;
bool checkPrime = true; //value of checkPrime must be true or false
cout << "Enter number: ";
cin >> num;
//check for prime number
for (i = 2; i <= num / 2; ++i)
{
if ((num % i) == 0)
{
checkPrime = false;
break;
}
}
if (checkPrime)
cout << "\n" << num << " is a prime number.\n";
else
cout << "\n"<< num << " is not a prime number.\n";
return 0;
}
Output
Enter number: 42 42 is not a prime number Enter number: 29 29 is a prime number
Explanation
This program also checks whether the number entered by the user is perfectly divisible by i
or not.
In this case, we have declared and initialized boolean variable checkPrime
to true
. If the num
is perfectly divisible by i
then checkPrime is set to false
.