Check prime number in C++ – Program to check if a number is a prime number or not in C++  with example.

What is Prime Number?

Prime number is number which is divided by 1 or itself and cannot be divided by other numbers. For example, 2,3,5,7,11 etc. are prime numbers.

Important points:

  • Value less than 2 are not prime numbers. In other words, negative numbers, 0 or 1 are not prime numbers.
  • Smallest prime number is 2

Simple C++ program to check prime number or not


/*---------------------------------
* C++ program to check if a number
* is prime number
*/
#include<string>
#include<iostream>
using namespace std;

bool isPrimeNumber(int num){

bool flag = true;

//1,0 or -ve numbers are not prime number
 //so, return from here
 if(num<=2)
 return false;

for(int i =2; i<= num/2;++i){

if(num%i==0){
 flag = false;
 break;
 }
 }

return flag;
}

/*---------------------------------
* Prime number test program
* */
int main(){

int num;
 bool flag = false;

cout<<"Enter the number"<<endl;
 cin>>num;

flag = isPrimeNumber(num);
 if(flag == true)
 cout<<"Number is a prime number"<<endl;
 else
 cout<<"Number is not a prime number"<<endl;

return 0;
}

TEST CASES:

Input: 22, output: Number is not a prime number
input 11: Output: Number is a prime number
input: 0, Output: Number is not a prime number
input: -1, Output: Number is not a prime number

Related Posts