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:
- Program to check whether entered number is palindrome or not.
- Program to check whether entered number is Armstrong Number or Not.
- Program to convert binary number to octal number.
- Program to convert binary number to decimal number.
- Program to convert binary number to hexadecimal number.
- Program to convert octal number to binary number.
- Program to convert octal number to decimal number.
- Program to convert octal number to hexadecimal number.
- Program to convert decimal number to binary number.
- Program to convert decimal number to octal number.
- Program to convert decimal number to hexadecimal number.
- Program to convert hexadecimal number to binary number.
- Program to convert hexadecimal number to octal number.
- Program to convert hexadecimal number to decimal number.
- Program to check Leap Year.
- Program to find Quotient and Remainder.
- Program to find largest amongst three numbers.
- Program to find factorial of a number.
- Program to find GCD of two numbers.
- Program to find LCM of two numbers.