Today we shall learn how to write a program to find a number is Prime number or not.Before we start writing a program we should learn the basic definition.A number is said to be prime number if”It is divisible by one and itself only”.Therefore while deciding a prime number we should about the factors of the given number.
To find the factors of the given number we should divide the number.If the remainder is 0 then number is divisible and it is said to be the factor of the given number.Here we shall use the modulous operator(%) to find the remainder.Let us write the code:
#include<iostream.h> #include<conio.h> class prime_number { public: int n; void calculating(); }; void prime_number :: calculating() { int flag=0,count=0; for(int i=2;i<n;i++) { count=0; if(n%i==0) { count++; flag++; } if(count !=0) cout<<"\nGiven number is divisible by"<<i; } if(flag ==0) cout<<"\n******Given number "<<n<<" is a prime number*******"; else cout<<"\n********There fore given number "<<n<<" is not a prime number*********"; } void main() { clrscr(); prime_number ob; cout<<"Enter the number to check for prime number:"; cin>>ob.n; ob.calculating(); getch(); }
Output:
You can download the code:download