C++ Program to Check Number Is Prime or Not

1. Introduction

Prime numbers have been a topic of fascination and study in mathematics for centuries. A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In simpler terms, if a number is prime, it doesn't have any divisors other than 1 and itself. In this blog post, we will learn how to write a C++ program to determine if a given number is prime or not.

2. Program Overview:

To check if a number is prime:

1. Acquire the number from the user.

2. If the number is less than 2, it's not prime.

3. For numbers 2 and above, check for factors up to the square root of the number.

4. If no factors are found, it's prime. Otherwise, it isn't.

3. Code Program

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

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

int main() {
    int num;
    
    // Prompting user for input
    cout << "Enter a number: ";
    cin >> num;

    if(isPrime(num)) {
        cout << num << " is a prime number." << endl;
    } else {
        cout << num << " is not a prime number." << endl;
    }

    return 0;
}

Output:

29 is a prime number.

4. Step By Step Explanation

1. Headers and Namespace: The iostream library is included for input-output operations and cmath for the sqrt function. We also declare usage of the standard namespace.

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

2. Prime Checking Function: The isPrime function checks if a given number n is prime or not. If the number is less than or equal to 1, it's not prime. For other numbers, we check for factors up to the square root of n to optimize the process.

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

3. Main Function Declaration: The main function is where the program starts its execution.

int main() {

4. Variable Declaration: An integer variable num is declared to store the user's input.

    int num;

5. User Input: We utilize cout to display a prompt and cin to get the user's input.

    // Prompting user for input
    cout << "Enter a number: ";
    cin >> num;

6. Prime Verification: The program checks the number using the isPrime function and displays the result using cout.

    if(isPrime(num)) {
        cout << num << " is a prime number." << endl;
    } else {
        cout << num << " is not a prime number." << endl;
    }

7. Program Termination: Execution ends and 0 is returned, signaling successful termination.

    return 0;

Comments