Sunday, 27 October 2013

Program to print out whether a number given is prime or not

This might be a little difficult to understand, so just be with me...
Let us revise some basic math first.

  • A Prime Number is a number which has no divisors other than 1 and that number itself. e.g.,  2, 5,7, 97 etc.
  • A Composite Number is just opposite to a prime number, which has one or more divisors other than 1 and that number itself. e.g., 4, 8, 9, 27.
In this program we are going to input a number from the user and show whether the number is prime or not prime. Here is the code:

/*Support us by subscribing, commenting, and viewing the 
blog frequently! - GeekyCircle Admin :)*/ #include<iostream.h> #include<conio.h> void main() { int num, i, counter=0; cout<<"Enter the number to be processed : "<<endl; cin>>num; for(i=2;i<=num/2;i++) { if(num%i==0) { counter=counter+1; //Or 'counter++;' break; } } if(counter==0) { cout<<"The number is a prime number"<<endl; } else { cout<<"The number is not a prime number"<<endl; } getch(); }

For newer IDEs (like Dev C++) :
/*Support us by subscribing, commenting, and viewing the 
blog frequently! - GeekyCircle Admin :)*/
#include<iostream>
using namespace std;
int main()
{
    int num, i, counter=0;
    cout<<"Enter the number to be processed : "<<endl;
    cin>>num;
    for(i=2;i<=num/2;i++)
    {
       if(num%i==0)
       {
           counter=counter+1; //Or 'counter++;'
           break;
       }
    }
    if(counter==0)
    {
        cout<<"The number is a prime number"<<endl;
    }
    else
    {
        cout<<"The number is not a prime number"<<endl;
    }
 return 0;
}
Working of the program

So basically what happens in the loop is :

  1.  i is initially 2. The loop checks if the remainder of the division num/i is 0. If it is 0, then a counter set at 0 becomes 1. i is incremented one be one to num/2. This is because, we need not check if, any number greater than the half of the input number is the factor of the input number (from basic math). 
  2. If the counter is more than 1 (i.e., at some point, i becomes a perfect divisor of the input number i.e., number is not prime), we output "The number is not prime" and the loop breaks. If the counter is 0 at the end of the loop(i.e., There is no umber that is the perfect divisor of the input number i.e., the number is prime) we output "The number is prime"
Let us consider two examples:

Suppose input number is 8.
  • Initially i is 2. 8%2 is 0. counter is incremented from 0 to 1 and the loop breaks since 8%2 is 0
  • Since counter is 1, output is "The number is prime".
Suppose the input number is 7. 
  • Initially i is at 2. First 7%2 is found out. 7%2 = 1. Loop continues since remainder is not 0.
  • i is incremented by 1. i is now 3. 7%3 is also 1. Loop breaks here since the next integer after 3 is 4 which is greater than half of 7. 
  • At the end counter is still 0. So the output is "The number is prime".

No comments:

Post a Comment

You might also like