C++ Program: Check if a Number is Prime

Program Code:

#include <iostream>
#include <cmath> // For sqrt function

using namespace std;

// Function to check if a number is prime
bool isPrime(int n) {
    // Corner cases
    if (n <= 1) {
        return false;
    }
    if (n <= 3) {
        return true;
    }

    // Check for divisibility from 2 to sqrt(n)
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

int main() {
    int number;
    cout << "Enter a number: ";
    cin >> number;

    // Check if number is prime and display result
    if (isPrime(number)) {
        cout << number << " is a prime number." << endl;
    } else {
        cout << number << " is not a prime number." << endl;
    }

    return 0;
}

Explanation of the Program

  1. Function isPrime:
    • bool isPrime(int n): This function takes an integer n as input and returns true if n is a prime number, and false otherwise.
    • Edge Cases: Numbers less than or equal to 1 (n <= 1) are not prime.
    • Optimization: For numbers greater than 1, the function checks divisibility from 2 up to the square root of n (sqrt(n)). This optimization reduces the number of checks needed.
  2. Main Function:
    • Prompts the user to enter a number.
    • Calls the isPrime function to check if the entered number is prime.
    • Displays the result based on the return value of isPrime.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)