Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Check if a number is prime or not (http://www.go4expert.com/forums/check-prime-t15284/)

aadilprabhakar 27Nov2008 18:17

Check if a number is prime or not
 

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 27Nov2008 18:21

Re: Check if a number is prime or not
 
You don't need to loop till i but even i/2 or square root of i is also sufficient.

back from retirement 30Nov2008 22:16

Re: Check if a number is prime or not
 
Yes....the actual is the square root of i. You can use the standard function sqrt(); for that purpose.

skp819 19Dec2008 13:23

Re: Check if a number is prime or not
 
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:";
        }
    }
}



All times are GMT +5.5. The time now is 03:21.