C++ program to check prime number
In this chapter of C++ program tutorial out task is:
-
Write a c++ program to check whether a number is prime or not.
C++ program to check a number is prime or not
Below is the C++ program to check a number is prime or not.
/* Program Name : To check whether a number is prime or not
Program Author : Sayantan Bose
*/
#include<iostream>
//math.h header file is used for the sqrt function
#include<math.h>
using namespace std;
//This is function that check whether a number is prime or not
//This is the function that returns true if it is prime or return false if it is not a prime number
bool isPrime(int number)
{
int factor;
if(number == 0 || number == 1)
return false;
for(factor=2;factor<sqrt(number);factor++)
{
if(number % factor == 0){
return false;
break;
}
}
return true;
}
//This is the main function
int main()
{
int number,IsPrime;
cout<<"Enter the number to check prime or not: "<<endl;
cin>>number;
IsPrime = isPrime(number);
if(IsPrime)
cout<<number<<" : is a prime number"<<endl;
else
cout<<number<<" : is not a prime number"<<endl;
return 0;
}
OUTPUT :
Enter the number to check prime or not:
17
17 : is a prime number
EXPLANATION :
In the above c++ program to check if a number is prime:
-
In the function isPrime has a return type bool i.e. either it will return true or false.
-
Then inside the function it is checked whether the number is divided by any factor other than the number itself and 1.
-
If the number is divided by the number itself or by 1 then the function return the true result else return false.
-
According to the value returned by the isPrime function the following statement is executed in main function.
You can see the above code execution and output in codeblocks IDE:
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Sayantan Bose
- š Iām currently working on DS Algo skills
- š± Iām currently learning web develeopement
- šÆ Iām looking to collaborate with Oppia
- š« Reach me at https://www.linkedin.com/in/sayantan-bose-14134a1a6/
- š Pronouns: his/him
Page Views :
Published Date :
Nov 26,2020