C++ prime number test – C++ Program to Check Prime Number

C++ prime number test: In the previous article, we have discussed C++ Program to check Whether a Number is Palindrome or Not. In this article, we will see C++ Program to Check Prime Number.

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

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

Know the collection of various Basic C++ Programs for Beginners here. So that you can attend interviews with more confidence.