1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Check if a number is prime or not

Discussion in 'C++' started by aadilprabhakar, Nov 27, 2008.

  1. aadilprabhakar

    aadilprabhakar New 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()
    {[INDENT]     int num,i;
    
        clrscr();
    
        cout<< "Please enter the number ";
        cin >> num;
        i =2 ;
    
    
         while(1){[INDENT]        if (num%i==0) {[INDENT]         if(num == i){[INDENT]             cout << "Prime Number";
                break;
    [/INDENT][/INDENT][INDENT]         } else {[INDENT]cout << "Not Prime";
    break;
    [/INDENT]}
    [/INDENT]} else {[INDENT]         i++;
    [/INDENT]}
    [/INDENT]}
    [/INDENT]}
    
     
  2. shabbir

    shabbir Administrator Staff Member

    You don't need to loop till i but even i/2 or square root of i is also sufficient.
     
  3. Yes....the actual is the square root of i. You can use the standard function sqrt(); for that purpose.
     
  4. skp819

    skp819 New Member

    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 a moderator: Dec 19, 2008

Share This Page