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

C++ProgrammingServer Side Programming

A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself. Some of the first prime numbers are −

2, 3, 5, 7, 11, 13 ,17

The program to check if a number is prime or not is as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int n=17, i, flag = 0;
   for(i=2; i<=n/2; ++i) {
      if(n%i==0) {
         flag=1;
         break;
      }
   }
   if (flag==0)
   cout<<n<<" is a prime number";
   else
   cout<<n<<" is not a prime number";
   return 0;
}

Output

17 is a prime number

In the above program, there is a loop that runs from 2 to half of n, where n is the number to be determined. Each of the values of the loop divide n. If the remainder of this division is 0, that means n is divisible by a number, not one or itself. So, it is not a prime number and the flag is set to 1. Then break statement is used to exit the loop.

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

If the value of flag remained zero, then the number is a prime number and that is displayed. If the value of flag was changed to one, then the number is not a prime number and that is displayed.

if (flag==0)
cout<<n<<" is a prime number";
else
cout<<n<<" is not a prime number";
raja
Published on 26-Sep-2018 16:01:38
Advertisements