Check if a number is prime or not

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

  1. aadilprabhakar

    aadilprabhakar New Member

    Joined:
    Nov 18, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    India

    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

    Joined:
    Jul 12, 2004
    Messages:
    15,368
    Likes Received:
    386
    Trophy Points:
    83
    You don't need to loop till i but even i/2 or square root of i is also sufficient.
     
  3. back from retirement

    back from retirement New Member

    Joined:
    Nov 9, 2008
    Messages:
    72
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Student, UG 1st Yr., Jadavpur University
    Location:
    Uttarpara, West Bengal, India
    Yes....the actual is the square root of i. You can use the standard function sqrt(); for that purpose.
     
  4. skp819

    skp819 New Member

    Joined:
    Dec 8, 2008
    Messages:
    89
    Likes Received:
    3
    Trophy Points:
    0
    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

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice