Processing math: 100%

Pages

Tuesday, 8 December 2015

Prime number detection using C++




Prime Number: It is a natural number other than 1 which has only two divisors, 1 and itself.

Examples:

3 is a prime number. It has two divisors 1 and 3 itself.
13 is a prime number. It has two divisors 1 and 13 itself.

Algorithm:

Steps:
  1. Take an integer to check whether it is prime or not.
  2. Divide the integer by the all the numbers from 1 to till that number
  3. Count the number of times the integer is divisible
  4. If the count is 2 then it is a prime number
  5. Otherwise it is not a prime number.

  
#include "iostream"
#include "conio.h"

using namespace std;

        int main()
        {

         int n, count=0;

        cout<< "Enter a number to check prime : ";
        cin>>n;

        for(int a=1;a<=number; a++)
            {
                if(number%a==0)
                {
                    count++;
                }
            }
        if(count==2)
            {
                cout<<" PRIME NUMBER \n";
            }
        else
            {
                cout<<" NOT A PRIME NUMBER \n";
            }

       return (0);
    }


INPUT:     Enter a number to check prime : 7
OUTPUT: PRIME NUMBER

INPUT:       Enter a number to check prime : 15
OUTPUT:  NOT A PRIME NUMBER

No comments:

Post a Comment