Check if a given number is a Prime number in C++

Today we are going to write a program to check if a given number is a Prime number in C++ programming language i.e. if a number enter by user is a prime number or not.

We all know what a Prime number is let’s recall quickly:

Prime Number: A number which is divisible by 1 and itself is called Prime number i.e. it do not have any factors. Let’s see how to check Prime numbers in a program.

Problem: Check if the number input by user is Prime or not.

Logic behind finding prime number:

  • Start finding the factors of the number from 1.
  • Count the total number of factors.
  • If number of factors are 2 then it is a Prime number otherwise not.

Program to check if a number is Prime number in C++:

#include<iostream>
using namespace std;

int main()
{
    int number,count=0;
    cout<<"Enter a number: ";
    cin>>number;
    for(int a=1;a<=number;a++)
    {
        if(number%a==0)
            count++;
    }
    if(count==2)
        cout<<"t"<<number<<" IS A PRIME NUMBER \n";
    else
        cout<<"t"<<number<<" IS NOT A PRIME NUMBER \n";
    return 0;
}

 

OUTPUT:

prime number in c++

Comment below in case you want to discuss more about the content shared above.

1 thought on “Check if a given number is a Prime number in C++”

Leave a Comment