C++ Program to Check if a Number is Prime Number or not

C++ Program to Check Whether the Number is Prime or Not

Prime number is a number which can be divided by 1 and itself i.e. a number which can not be divided by any other number other than 1 or itself is a prime number.
 
Example: 2,3,5,7,11….so on  are the prime number as we can see they only have two divisors, 1  and the number itself.
C++ program to check whether a number is prime or not

Algorithm:-

  1. Take input number n
  2.  Initialize i=1
  3.  Initialize div=0
  4.  we have to count all the divisor of number from 1 to n
  5.  run a loop from i=1 to n
    1. if n%i==0  (if n is divisible by i)
      1. increment div, div++
    2. increment i by 1 ,i++
  6. check div, if div==2 display prime, else display not prime
C++ Program to Check if a Number is Prime Number or not

C++ Code

#include<iostream>
using namespace std;
main()
{
    int i=1,num,div=0; //initializing variables
    cout<<"Enter number:"; cin>>num; //user input
    for(i=1;i<=num;i++) //checking for number of divisor
    {
        if(num%i==0)
      {
          div++; 
      }
    }
   if(div==2) //no divisors other than 1 and itself
   {
       cout<<num<<" is a prime number";
   }
   else
   {
       cout<<num<<" is not a prime number";
   }
   return 0;
}

Output

Enter number:3
3 is a prime number