RSS Forums RSS
Please support our C++ advertiser: Programming Forums

Program that determines if a number is prime

Join Date: Dec 2004
Location: Allentown, PA
Posts: 60
Reputation: murschech is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 1
murschech murschech is offline Offline
Junior Poster in Training

Re: Program that determines if a number is prime

  #8  
Jul 1st, 2005
Your program doesn't make use of the efficiencies I mentioned. For one thing, you test possible factors up to valuex/2 but you only have to go up to sqrt(valuex), which is much smaller. (For example, sqrt(100) is 10, much less that 100/2.) Also you increment trial divisors by one rather than 2. Finally, once you find a divisor (and so, you know the number's not a prime), you contiinue to try more divisors!

Here's my version.
#include <iostream>
using namespace std;

bool isaprime(long);

bool isaprime(long x)
{   long n;
    // is 2 a divisor?
    if ( x%2 == 0)
       return false;
    n = 3;
    while (n*n <=x)
    {   if (x%n == 0)
           return false;
        n += 2;
    }
    return true;
}

int main()
{   long x;
    while (1)
    {   cout <<"Enter a positive integer to check for primality, 0 to exit: ";
        cin >> x;
        if (x == 0)
        {   cout << "Thanks for the fun. Come again.\n";
            return 1;
        }
        if (isaprime(x))
           cout <<x<<" is a prime\n";
        else
           cout <<x<<" is not a prime\n";

   }

}
<< moderator edit: fixed [code][/code] tags (forward slash) >>
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 11:05 am.
Newsletter Archive - Sitemap - Privacy Statement - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC