PRIME NUMBER
A natural number (>1) is said to be a prime number if it is completely divisible by 1 and itself only. A number which is not prime is called Composite number.
eg. 2,3,5,7,11,13 etc are Prime Numbers.
STEPS
In order to find given number is prime or not,
1. Initialize a counter(i) with 2 and a boolean variable (flag) as true.
i = 2;
flag = true;
2. Check the divisibility of the number with i.
num % i==0
3. If the number is divisible by i, then it cannot be a prime number. So, set flag as false and break from loop.
flag = false;
break;
4. If the number is not divisible by i, then increment i and goto step 2 until i <=(num/2).
i++;
5. If flag remains true throughout the above steps, it signifies that it is not divisible by any number between 2 and num/2 i.e. It is a prime number.
If flag is false then the number is divisible by some number and is not a prime number.
PROGRAM
//Program to check whether given number is Prime or Not
#include <iostream>
using namespace std;
int main()
{
int num , i;
bool flag=true;
cout<<"ENTER A NUMBER: ";
cin>>num ;
for( i=2 ; i<=(num/2) ; i++ )
{
if(num % i==0)
{
flag=false;
break; //Exit from the Loop
}
}
if(flag==true)
{
cout<<num<<" IS A PRIME NUMBER ";
}
else
{
cout<<num<<" IS A COMPOSITE NUMBER ";
}
return 0;
}
OUTPUT