Example : 2 , 3 , 5 are primes . because 3 can only divide on 1 and itself.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int number; //Declare Integer Variable
int count = 0; //For count the divisors
cout << "Enter Number To Check ";
cin >> number;
for (int i = 1; i<=number; i++)
{
if (number%i == 0)
{
count++;
}
}
if (count == 2)
{
cout << "\n Number is Prime" << endl;
}
else
{
cout << "\n Number is Not Prime " << endl;
}
getche();
}
Understanding the logic behind the program Prime Number :
- From definition we get that the prime number have only two dividers.
- To check total number of divided we check it from 1 to itself.
- In C++ Program we declare two variables "number" to get the number from user and check it
and "count" to count the number dividers and initialize the count with 0. - Now we take a FOR LOOP and start from 1 to itself. In FOR LOOP we take a IF condition
and if condition gets true its increment in count by 1. - When LOOP is end it go to IF condition and check if count equals to 2 it print Prime Number else not a prime .
- The numbers which are not Prime have dividers greater than 2.
0 comments:
Post a Comment