c-plus-plus
  1. c-plus-plus-prime-number

C++ Program to Check for Prime Number

A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In this C++ program, we will write a function to check whether a given number is prime or not.

Syntax

bool isPrime(int num) {
    // code
}

Example

#include <iostream>
using namespace std;

bool isPrime(int num) {
    if (num <= 1)
        return false;
    for (int i = 2; i <= num / 2; i++) {
        if (num % i == 0)
            return false;
    }
    return true;
}

int main() {
    int num;
    cout << "Enter a positive integer: ";
    cin >> num;
    if (isPrime(num))
        cout << num << " is a prime number." << endl;
    else
        cout << num << " is not a prime number." << endl;
    return 0;
}

Output

Enter a positive integer: 17
17 is a prime number.

Explanation

In the above C++ program, we have defined a function isPrime which takes an integer as input and returns true if it is a prime number and false otherwise.

The function first checks if the input number is less than or equal to 1, as any number less than or equal to 1 is not considered prime. Then, the function checks if the number is divisible by any integer between 2 and half of the number (inclusive). If the number is divisible by any integer, it is not prime. Otherwise, it is a prime number.

Use

The isPrime function can be used in situations where we need to identify if a given number is prime or not. This is especially useful in mathematical or scientific applications.

Important Points

  • A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
  • A number less than or equal to 1 is not considered prime.
  • To check if a number is prime, we need to divide it by all the integers between 2 and half of the number (inclusive).

Summary

In this C++ program, we have defined a function to check whether a given number is prime or not. We have used a for loop to iterate over all the integers between 2 and half of the number to check for divisibility. We have also included input validation to check if the input number is greater than 1.

Published on: