Nov 30, 2016

Program: Check given number for Prime Number

Program: Check given number for Prime Number

We know about prime number is a number which is greater than one and can only divide by 1 or by its own number. In this program we check the given number for prime number.

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter Prime Number: ";
        cin >> n; //input number
//initialize flag for true assume given number is prime number
bool flag = true; 
//if number is less than 2 than its not a prime number according to def
if(n<2)
flag = false; 
else if(n == 2) // if n is 2 than its prime number
flag = true;
        else if(n%2 ==0)
              flag = false;
else{
/*
   Now we check n > 2 whether its prime or not. We check for 2 earlier because from now on we are gonna skip all even number as other than 2 there are no even prime number as all divisible by 2. So we start with 3 and check up to n with increment of two in one loop. So if any number less than n found divisible with n then set flag to false and break the loop.
*/
for(int i=3;i<n;i+=2){
if(n%i == 0)
{
flag = false;
 break;
}
}
}
//print output according to flag value
if(flag)
cout<<"It is a Prime Number";
else
cout<<"It is Not a Prime Number";
return 0;  //https://cplspls.blogspot.com
}

OUTPUT:


0 comments:

Post a Comment