C++ Program to Check Whether a Number is Prime or Not

In this program, we will learn how to check whether a number is prime or not using C++ Programming language.

Prime Number is a positive integer which is only divisible by 1 and itself.
For example: 29 is a prime number because it is only divisible by 1 and 29, but, 15 is not because it is divisible by 1, 3, 5 and 15.

We will discuss two ways to do it.

  1. Traversing till half the given number
  2. Traversing till square root of the given number

Let's discuss them one by one.

Check whether a number is prime or not

In this program, we ask the user to enter a number and store it in variable num.

Then, for loop is executed which checks whether the number entered by the user is perfectly divisible by i or not.

The for loop initiates with an initial value of i equals to 2 and increasing the value of i in each iteration.

If the number entered by the user is perfectly divisible by i then, isPrime is set to false and the number will not be a prime number.

But, if the number is not perfectly divisible by i  until test condition i <= n/2 is true means, it is only divisible by 1 and that number itself.

Traversing till half the given number

Code:-

#include <iostream>  

using namespace std;  

int main(){  
    int num;
    bool isPrime = true; 

    cout << "Enter the Number: ";  
    cin >> num; 

    if(num <= 1){
        isPrime = false;
    }

    for(int i = 2; i <= num/2; i++){  
        if(num % i == 0){  
            isPrime = false;  
            break;  
        }  
    }  

    if (isPrime)  
        cout << num << " is Prime." << endl;  
    else
        cout<< num << " is not Prime." << endl;  

    return 0;  
}

Output:-

Enter the Number: 2
2 is Prime.
Enter the Number: 29
29 is Prime.

Traversing till square root of the given number

In this, we just have used the sqrt() function of the math library to get the square root of the number. Now, for loop will traverse till the square root of the given number (num variable).

Code:-

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

using namespace std;  

int main(){  
    int num;
    bool isPrime = true; 

    cout << "Enter the Number: ";  
    cin >> num; 

    if(num <= 1){
        isPrime = false;
    }

    for(int i = 2; i <= sqrt(num); i++){  
        if(num % i == 0){  
            isPrime = false;  
            break;  
        }  
    }  

    if (isPrime)  
        cout << num << " is Prime." << endl;  
    else
        cout<< num << " is not Prime." << endl;  

    return 0;  
}

Output:-

Enter the Number: 53
53 is Prime.
Enter the Number: 67
67 is Prime.

You can learn about many other C++ Programs Here.







The following two tabs change content below.
Amit Rawat

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...