The number which is only divisible by one and itself is called prime number.For example 13 is a prime number which is only divisible by 1 and 13.There are various way to find prime number but here we provide an easy C++ program to check number is prime or not .
#include<conio.h>
void main()
{
int num,p=0;
cout<<"\n Enter a number : ";
cin>>num;
for(int i=2;i<=num;i++)
{
if(num%i==0)
{
p++;break;
}
}
if(p==0)
{
cout<<"\n Number is prime";
}
else
{
cout<<"\n Number is not prime";
}
getch();
}
Logic of the program
There are many methods to construct a program to check whether a number is prime or not in C++ , this methods uses for loop for the program.
- First you should know the concept of prime number.
- Now Prime is a number which is divisible only by 1 or itself.
- So if the number to be checked is divided with certain number other than 1 or itself, and the remainder is zero, this means that the number is not prime as it has been fully divided by another number.
- Every number is divisible by 1 so exclude the 1 and start the loop from 2 to the number to be checked,
- Then divide the number with every number from 2 to less than that number and then if the number is not divisible then the number is prime number
C++ program to check number is prime or not
#include<iostream.h>#include<conio.h>
void main()
{
int num,p=0;
cout<<"\n Enter a number : ";
cin>>num;
for(int i=2;i<=num;i++)
{
if(num%i==0)
{
p++;break;
}
}
if(p==0)
{
cout<<"\n Number is prime";
}
else
{
cout<<"\n Number is not prime";
}
getch();
}
Output 1
Enter a number : 13
Number is prime
Output 2
Enter a number : 15
Number is not prime