A number which is only divisible by itself and 1 is known as prime number, for example: 5 is a prime number because it is only divisible by itself and 1.

This program takes the value of num (entered by user) and checks whether the num is prime number or not.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
int main()
{
  int n, i;
  bool isPrime = true;
  cout << "Enter a positive integer: ";
  cin >> n;
  for(i = 2; i <= n / 2; ++i)
  {
      if(n % i == 0)
      {
          isPrime = false;
          break;
      }
  }
  if (isPrime)
      cout << "This is a prime number";
  else
      cout << "This is not a prime number";
  return 0;
}

Another Example: 

#include <iostream>
using namespace std;
int main(){
   int num;
   bool flag = true;
   cout<<"Enter any number(should be positive integer): ";
   cin>>num;

   for(int i = 2; i <= num / 2; i++) {
      if(num % i == 0) {
         flag = false;
         break;
      }
   }
   if (flag==true)
      cout<<num<<" is a prime number";
   else
      cout<<num<<" is not a prime number";
   return 0;
}


Output:
Enter any number(should be positive integer): 149
149 is a prime number

You can also use while loop to solve this problem, just replace the following code in above program:
for(int i = 2; i <= num / 2; i++) {
   if(num % i == 0) {
      flag = false;
      break;
   }
}

Post a Comment

 
Top