Basically, what is Prime number? Prime number is a number that cannot be divided by any other number except by number 1 and by itself.
In this articles we will develop a C++ program to find if the given number is prime or not
So let’s get started
#include <iostream> #include <conio.h> using namespace std; int main() { int hit=0,number,m; cout<<"Program to find Prime Number"<<endl; cout<<"Enter any number"<<endl; cout<<"Number: "; cin>>number; for (m=1;m<=number;m++) { if (number%m==0) { hit++; } } if (hit==2) { cout<<"The Number is Prime"; } else { cout<<"The Number is not Prime"; } getch(); return 0; }
Explaination
When the Program Run, it will ask for number from the user. When user enter the number, the program will run a for loop and inside the loop there is an if statement that check if the number is divisible by the number in the loop.
If the number is divisible by the number in the loop, the variable hit will get increment.
After the condition in the loop becomes false. It will exit the loop.
In line 18 the if condition will check if hit is equal to 2. If hit is equal to 2. Then the number is a prime number else the number is not a prime number
Compiler Used: CodeBlock