Program to check Whether a Number Prime or Not in C++

 Prime Number Program in C++


Prime Number : 

                    A number which is divisible only by itself and one is called as Prime Number. Let us understand with an example, 7 is a prime number because it is only divisible by only 1 and itself. whereas 9 is not a prime number because it is divisible by 1, 3 & 9.

Program to Check Prime Number

Logic :

  • Input a number
  • Create a function to check number is prime or not
  • Check whether the number is only divisible by 1 and itself or not
  • If divisible print prime else print not prime 

Code :

#include<bits/stdc++.h>
using namespace std;

int isprime(int a)
{
    int i,c=0;
    for(i=2;i<=sqrt(a);i++)
    {
        if(a%i==0)
        {
            c=1;
            break;
        }
    }
    if(c)
    {
        return 0;
        
    }
    return 1;
}

int main()
{
    int n;
    cin>>n;
    if(isprime(n))
    {
        cout<<"prime";
    }
    else
    {
        cout<<"not prime";
    }
    return 0;
}

***


Post a Comment

0 Comments