Skip to content

Prime number program in c++

  • by
prime number program in c++

Here’s an example program in C++ that checks whether a given number is prime or not:

#include <iostream>

using namespace std;

bool isPrime(int n) {

    if (n <= 1) {

        return false;

    }

    for (int i = 2; i*i <= n; i++) {

        if (n % i == 0) {

            return false;

        }

    }

    return true;

}

int main() {

    int num;

    cout << “Enter a number: “;

    cin >> num;

    if (isPrime(num)) {

        cout << num << ” is a prime number.\n”;

    } else {

        cout << num << ” is not a prime number.\n”;

    }

    return 0;

}

In this program, the isPrime() function takes an integer n as its argument and returns true if it is a prime number, or false otherwise. The function uses a simple algorithm to check for primality: it tests whether n is divisible by any integer from 2 up to the square root of n. If n is divisible by any of these integers, then it is not a prime number.

In the main() function, the program prompts the user to enter a number, reads the input using cin, and then calls the isPrime() function to check whether the number is prime or not. The program then prints the result to the console using court.

Also, read An Introduction to Hypertext Markup Language (HTML): Benefits, Syntax, and Usage