Monday 7 December 2015

HOW TO IDENTIFY WHETHER A NUMBER IS PRIME OR NOT C++!

A very interesting question to be done in programming is how to check that whether this number is prime or not.
So here we are gonna help you out that how to do it, we are going to tell you the basic code how to identify if a number is prime or not.
there are many methods to write or initialize the variable, understand the logic 
#include<iostream>
using namespace std;

int main()
{
     int n;
     int i;
     int f=0;  \\use for test, you can also use bool flag.
                    \\recall the defination of prime number, only divisible by 1 or itself
     cout<<"enter number to confirm"<<endl;
     cin>>n;
     for ( i=2;i<n-1;i++);
         {
         if (n%i==0)
            {
                f=1;
             }
         }
\\this above for loop will divide the given number, let say 7, with all the number from 2 to 6, if it would be divisible our testing variable will change its value.
     if (f==1)
        {
          cout<<n<<"is not a prime number"<<endl;
        }
     if (f==0)
        {
         cout<<n<<"is a prime number"<<endl;
        }  \\you can use if else condition as well
system("pause");
return 0;
}

No comments:

Post a Comment