Check if a number is prime or not

aadilprabhakar's Avatar, Join Date: Nov 2008
Newbie Member

To check if the number is prime or not.





Code:
/*
    To check if an integer is prime or not
*/

#include<iostream.h>
#include<conio.h>
void main()
{
int num,i; clrscr(); cout<< "Please enter the number "; cin >> num; i =2 ; while(1){
if (num%i==0) {
if(num == i){
cout << "Prime Number"; break;
} else {
cout << "Not Prime"; break;
}
} else {
i++;
}
}
}
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
You don't need to loop till i but even i/2 or square root of i is also sufficient.
back from retirement's Avatar, Join Date: Nov 2008
Contributor
Yes....the actual is the square root of i. You can use the standard function sqrt(); for that purpose.
skp819's Avatar
Contributor
A simple program is here. to chech a number is prime or not.
Code:
void main()
{
    int a,b,i;
    cout<<"\n enter the no: ";
    cin>>a;
    for(i=2;i<=a;i++)
    {
        rem=a%i;
        if(rem==0)
        {
            cout<<"\nNo is not prime: ";    
        }
        else
        {
            cout<<"\nNo is  prime:";
        }
    }
}

Last edited by shabbir; 19Dec2008 at 14:16.. Reason: Code block