Prime number in c++ using function – C++ Program to Check Prime Number Using Function

Prime number in c++ using function: In the previous article, we have discussed C++ Program to Check Prime Number. In this article, we will see C++ Program to Check Prime Number Using Function.

C++ Program to Check Prime Number Using Function

  • Write a C++ program to check whether a number is prime number or not using function.

In this program, we will learn about prime numbers and how to check whether a number is prime number or not. Here s the formal definition of prime numbers:

Prime number is a natural number greater than 1 that is only divisible by either 1 or itself. In other words, a prime is not divisible by any other number other than itself. All numbers other than prime numbers are known as composite numbers.

First few prime numbers are : 2 3 5 7 11 13 17 19 23 29 …

C++ program to check a prime number using function

C++ program to check a prime number using function

// C++ program to check prime number
#include <iostream>
using namespace std;
  
bool isPrimeNumber(int num);
 
int main() {
  int num;
  cout << "Enter a positive number\n";
  cin >> num;
    
  if(isPrimeNumber(num))
      cout << num << " is a Prime Number";
  else
      cout << num << " is NOT a Prime Number";
        
  return 0;
}
 
bool isPrimeNumber(int num){
  bool isPrime = true;
  int i;
  // 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=false;
          break;
      }
  }
 
  return isPrime;
}

Output

Enter a positive number
13 
13 is a Prime Number
Enter a positive number
15 
15 is NOT a Prime Number

In this program, we first take an integer as input from user using cin and store it in a variable num. We then call isPrimeNumber function by passing num to check whether num is prime number or not.

Here we defined a function isPrimeNumber which check whether a number is prime number or not. If number is prime then it returns true otherwise false. To test whether a number is prime or not we are using brute force approach by testing whether num is a multiple of any integer between 2 and num/2. If num is divisible by any number between 2 and num/2 then num is not a prime number.

This is the most basic method of checking the primality of a given integer num and is called trial division.

Finally, based on the return value of isPrimeNumber function, we display message on screen saying whether number is prime number or not.

Start writing code in C++ language by referring to Simple C++ Program Examples available here. These examples are helpful to get an idea on the format, function used in every basic program.