C++ Program to check whether a Number is Prime or not

To check if a number is prime or not in C++

 

Here , in this section we will discuss  a program to check if a number is prime or not in C++. A number is said to be Prime Number if and only if it is divisible by one and itself.

  • Sample test case 1 :
    Input : 12
    Output :The given number is not a prime number. 
    Explanation : As 12 is divisible by 1, 2,  3, 4, 6 and 12 so, it is not a prime number.

  • Sample test case 2 :
    Input : 23
    Output :The given number is a prime number. 
    Explanation : 23 is divisible by 1 and 23, so it is a prime number.

 

Program to check a number is prime or not in C++

Algorithm :

  • Take the number from the user and store it in variable n.
  • Initialize the variable flag with value 0.
  • Run a loop from 2 to sqrt(n)
  • Check for every value if n is divisible by any number then set flag =1 and break the loop.
  • If flag = 0 then print the given number is prime.
  • Else print the number is not prime.

C++ Program based on above algorithm

#include<bits/stdc++.h>
using namespace std;

int main ()
{
int n, flag = 0;

cout << "Enter the number to check if it is prime or not: ";
cin >> n;

for (int i = 2; i <= sqrt (n); i++)
{
if (n % i == 0){
flag = 1;
break;
}
}

if (flag == 0)
cout << "The given number is prime";
else
cout << "The given number is not prime";

return 0;
}
Output :

Enter the number to check if it is prime or not: 23

The given number is prime