





Please login
Prime

Prepinsta Prime
Video courses for company/skill based Preparation
(Check all courses)
Get Prime Video
Prime

Prepinsta Prime
Purchase mock tests for company/skill building
(Check all mocks)
Get Prime mock
C++ Program to Check if a Number is Prime Number or not
C++ Program to Check Whether the Number is Prime or Not
Prime number is a number which can be divided by 1 and itself i.e. a number which can not be divided by any other number other than 1 or itself is a prime number.
Example: 2,3,5,7,11….so on are the prime number as we can see they only have two divisors, 1 and the number itself.


Algorithm:-
- Take input number n
- Initialize i=1
- Initialize div=0
- we have to count all the divisor of number from 1 to n
- run a loop from i=1 to n
- if n%i==0 (if n is divisible by i)
- increment div, div++
- increment i by 1 ,i++
- if n%i==0 (if n is divisible by i)
- check div, if div==2 display prime, else display not prime
C++ Code:-
//C++ Program
//Check Prime or Not
#include<iostream>
using namespace std;
int main()
{
int i,num,div=0; //initializing variables
cout<<“Enter number:”;
cin>>num; //user input
for(i=1;i<=num;i++) //checking for number of divisor
{
if(num%i==0)
{
div++;
}
}
if(div==2) //no divisors other than 1 and itself
{
cout<<num<<” is a prime number”;
}
else
{
cout<<num<<” is not a prime number”;
}
return 0;
}
Output
Enter number:31
31 is a prime number
- Positive or Negative number: C | C++ | Java
- Even or Odd number: C | C++ | Java
- Sum of First N Natural numbers: C | C++ | Java
- Sum of N natural numbers: C | C++ | Java
- Sum of numbers in a given range: C | C++ | Java
- Greatest of two numbers: C | C++ | Java
- Greatest of the Three numbers: C | C++ | Java
- Leap year or not: C | C++ | Java
- Prime number: C | C++ | Java
- Prime number within a given range: C | C++ | Java
- Factorial of a number: C | C++ | Java
- Sum of digits of a number: C | C++ | Java
- Reverse of a number : C | C++ | Java
- Palindrome number: C | C++ | Java
- Armstrong number : C | C++ | Java
- Armstrong number in a given range : C | C++ | Java
- Fibonacci Series upto nth term : C | C++ | Java
- Factorial of a number : C | C++ | Java
- Power of a number : C | C++ | Java
- Factor of a number : C | C++ | Java
- Strong number : C | C++ | Java
- Perfect number : C | C++ | Java
- Automorphic number : C | C++ | Java
- Harshad number : C | C++ | Java
- Abundant number : C| C++ | Java
- Friendly pair : C | C++ | Java

Login/Signup to comment