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

C++ prime number program help

Join Date: Sep 2005
Posts: 1
Reputation: Pcyther is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 1
Pcyther Pcyther is offline Offline
Newbie Poster

Re: C++ prime number program help

  #9  
Sep 4th, 2005
Hello My friend, I do not know if my response will be in time for you but here is a master code for finding all prime numbers up to any number 'x' that you input...


# include <cmath>          // This library enable the use of sqrt.
# include <iostream>
using namespace std;

void primenum(long double);     // Prototype...
int c = 0;

int main()
{
long double x = 0;
cout<<"\n This program will generate all prime numbers up to the"
    <<"\n number you have entered below...\n";
cout<<"\n Please enter a number: ";
cin>> x;

cout<<"\n Here are all the prime numbers up to "<<x<<".\n";
primenum(x);            //function invocation...
cout<<endl<<"\nThere are "<<c
    <<" prime numbers less than or equal to "<<x<<".\n\n";

return 0;
}

// This function will determine the primenumbers up to num.
void primenum(long double x)
{
    bool prime = true;                  // Calculates the square-root of 'x'
    int number2;
     number2 =(int) floor (sqrt (x));

    for (int i = 1; i <= x; i++){       
        for ( int j = 2; j <= number2; j++){
            if ( i!=j && i % j == 0 ){      
                prime = false;
                break;
            }
        }
        if (prime){
            cout <<"  "<<i<<" ";
            c += 1;
        }
        prime = true;
    }
}


// In you need any explanation for any parts of this program send me a message and i will reply as soon as i can...
Last edited by Dave Sinkula : Sep 4th, 2005 at 12:07 pm. Reason: Added [code][/code] tags.
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 6:41 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC