Home C++ Determine if the Number is Prime in C++

Determine if the Number is Prime in C++

In this example we show how to tell if a number is a prime number or not in C++

Lets first talk about what a prime number is

A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.

A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself.

However, 4 is composite because it is a product (2 × 2) in which both numbers are smaller than 4.

Example

 

#include <iostream>
#include <math.h>

using namespace std;

//Returns true if the given number is a Prime number
bool isPrime(int n)
{
    if (n == 1)
        return false; // as 1 is not a prime number

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

    return true;
}

int main()
{
    cout << "Is a Prime or not.\n";
    //variable declarations
    int number;
    bool prime = false;

    //taking input from the user
    cout << "Enter a positive integer other than 1 :  ";
    cin >> number;

    //Calling a method that returns true if the number is Prime
    prime = isPrime(number);

    if (prime)
    {
        cout << "\n\nThe number " << number << " is a Prime number.";
    }
    else
    {
        cout << "\n\nThe number " << number << " is not a Prime number.";
    }

    cout << "\n";

    return 0;
}

When you run this you will see something like this

Is a Prime or not.
Enter a positive integer other than 1 :  9


The number 9 is not a Prime number.

--------------------------------
Process exited after 4.384 seconds with return value 0
Press any key to continue . . .

You may also like