C++ Program to Check Prime Number Using a Function



In this article, we will show you how to check whether a number is prime by creating a function in C++. A prime number is a number greater than 1 that has no divisors other than 1 and itself.

For example, 2, 3, 5, 7, and 11 are prime numbers because they have only two divisors (1 and themselves), whereas 4, 6, 8, and 9 are not prime.

Using a Function to Check Prime Number

To check if a number is prime, we define a function that performs the check and returns true if the number is prime or false if it's not. Here are the steps we took:

  • First, we created a function that takes a number as input.
  • Then, we checked for divisibility from 2 up to the square root of the number.
  • Next, if the number is divisible by any of these values, we returned false because it's not a prime number.
  • Finally, if no divisors were found, we returned true, meaning the number is prime.

C++ Program to Check Prime Number by Creating a Function

Below is a C++ program where we define a function called isPrime() that takes a number and checks if it is a prime number using the steps mentioned above:

#include <iostream>
#include <cmath>
using namespace std;

// Function to check whether a number is prime
bool isPrime(int num) {
    if (num <= 1) {
        return false; // 0 and 1 are not prime
    }
    for (int i = 2; i <= sqrt(num); i++) {
        if (num % i == 0) {
            return false; // If divisible by any number, not prime
        }
    }
    return true; // If no divisors found, it's prime
}

int main() {
    int number = 29; // Number to check
    
    cout << "The number to check is: " << number << endl;
    
    if (isPrime(number)) {
        cout << number << " is a prime number." << endl;
    } else {
        cout << number << " is not a prime number." << endl;
    }
    
    return 0;
}

The output below shows the result of checking whether the given number is a prime or not.

The number to check is: 29  
29 is a prime number.

Time Complexity: O(sqrt(n)), because we only check divisibility up to the square root of the number.

Space Complexity: O(1), since we are using only a constant amount of extra space.

Updated on: 2025-05-09T16:05:32+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements