Check Prime Number

Check prime number” is again very basic problem of programming exercise. Here, we are given a number, entered by user and our task is to check whether entered number is prime number or not.

Prime Number: A number is said to be prime number if it is only divisible by 1 and by itself. 

Examples of Prime numbers are 2,3,5,7,11,…

NOTE: 1 is not a prime number.

Example (Check Prime Number):

INPUT: 
Number = 7
OUTPUT:
7 is a prime number.
INPUT: 
Number = 9
OUTPUT:
9 is not a prime number.

To check whether a number is prime number or not, we will check whether entered number is divisible from numbers 2 to (number-1). If any number from that range is divisible by entered number, then it is not a prime number. Else, it is a prime number.

C++ Program to check prime number is as follows:

/* C++ Program to check prime number */
#include<bits/stdc++.h>  
using namespace std;  
int main()  
{  
    int num;  
      
    //Scan the number  
    cout<<"Enter the number:";  
    cin>>num;  
      
    bool res = true;  
    /*  
    We will check whether entered number is  
    divisible by numbers from 2 to (num-1). 
    If entered number is divisible by any number 
    from 2 to (num-1), then it is not prime number. 
    Else, it is prime number. 
    */   
    for(int i = 2 ; i < num ; i++)  
    {  
        if(num % i == 0)  
        {  
            res = false;  
            break;  
        }  
    }  
      
    if(res == true && num!=1) /* 1 is not a prime number */  
    cout<<num<<" is a prime number";  
    else  
    cout<<num<<" is not a prime number";  
}  

OUTPUT:
Enter the number: 11
11 is a prime number

Related Posts:

  1. Program to check whether entered number is palindrome or not.
  2. Program to check whether entered number is Armstrong Number or Not.
  3. Program to convert binary number to octal number.
  4. Program to convert binary number to decimal number.
  5. Program to convert binary number to hexadecimal number.
  6. Program to convert octal number to binary number.
  7. Program to convert octal number to decimal number.
  8. Program to convert octal number to hexadecimal number.
  9. Program to convert decimal number to binary number.
  10. Program to convert decimal number to octal number.
  11. Program to convert decimal number to hexadecimal number.
  12. Program to convert hexadecimal number to binary number.
  13. Program to convert hexadecimal number to octal number.
  14. Program to convert hexadecimal number to decimal number.
  15. Program to check Leap Year.
  16. Program to find Quotient and Remainder.
  17. Program to find largest amongst three numbers.
  18. Program to find factorial of a number.
  19. Program to find GCD of two numbers.
  20. Program to find LCM of two numbers.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *