C++ Program to Check Prime Number

  • Write a C++ program to check whether a number is prime number or not.
  • How to test whether a number is prime number(Primality testing).

C++ Program to check Prime number

#include<iostream>

using namespace std;

int main() {
  int num, i, isPrime=0;
  cout << "Enter a Positive Integer\n";
  cin >> num;
  // Check whether num is divisible by any number between 2 to (num/2)
  for(i = 2; i <=(num/2); ++i) {
      if(num%i==0) {
          isPrime=1;
          break;
      }
  }
   
  if(isPrime==0)
      cout << num << " is a Prime Number";
  else
      cout << num << " is not a Prime Number";
       
  return 0;
}
Output
Enter a Positive Integer
23
23 is a Prime Number
Enter a Positive Integer
21
21 is not a Prime Number