How we can check Prime numbers

To check prime numbers we have to know that prime numbers are those numbers which can not be divided by any integer without 1 and the number itself. Consider a number 7.

Now, 7 is only divisible by 1 and 7. So, 7 is a prime number. We already have discussed broadly about prime numbers in C language. Here, we will see C++ programs to check prime numbers.

2, 3, 5, 7, 11, 13, 17, 19 23 etc are some of the smaller prime numbers. 2 is the only prime number which is even. To check a number that is it prime or not, we have to check that the number can be divided by at last one integers without 1 and the number itself.

C++ program to check prime numbers

In this C++ program we will take a number as input from the user and check whether the number is prime or not. To check prime number we can implement different logic. Let’s see a program to check a number that it is prime or not bellow.

// c++ program check prime numbers

#include <iostream>
using namespace std;

int main(){

  int number, k, rem = 0;

  cout << "Enter a number to check it : ";
  cin >> number;

  for(k = 2; k <= number/2; k++){

      if(number % k == 0){
          cout<< "\n" << number << " is not a prime number." <<endl;
          rem = 1;
          break;
      }

  }

  if(rem == 0){
      cout << "\n" << number << " is a prime number."<<endl;
  }

  return 0;

}

Output of checking prime number program

c-program-to-check-prime-number-prime-number-program-in-c

To practice more program related to prime number take idea from our prime numbers in C article. The logic will be same and what you have to do is implementing your C++ code. So, try this.

Previous pageAdd complex numbers

Next pageSum of digits