

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A c++ console application implementation of the sieve of eratosthenes algorithm using classes, constructors, and destructors. The application defines two classes, filter and sieve, to build a list of prime filters through a sieving process. The main function filters all prime numbers up to a given number and displays the number of primes found.
Typology: Assignments
1 / 2
This page cannot be seen from the preview
Don't miss anything!


Com S 229 Spring 2007 Dr. Markus Lumpe 1
Problem 1 Sieve of Eratosthenes: We start with the integer number 2, which is the first prime. To obtain the rest of the primes, we continue by filtering the multiples of 2 from the rest of the integers. This leaves a list beginning with 3, which is the next prime. Now we filter the multiples of 3 from the rest of that list. This leaves a list beginning with 5, which is the next prime, and so on. In other words, we construct the primes by a sieving process, described as follows: To sieve the integer numbers from 2 to N, build a list of prime filters, whose first element is a filter for the integer 2 and the rest of which is obtained by filtering all multiples of 2 out of the rest to N and generating a new prime filter for each new prime number found: Implement a C++ console application that defines a prime filter as outlined above. In order to implement the application define the following two classes: class Filter { private : Sieve& fSieve; int fPrime; Filter* fNext; static int fNumberOfFilters; public : Filter( Sieve& aSieve, int aPrime ); ~Filter(); void check( int aNumber ); int getNumber(); static int getNumberOfPrimes(); };
Com S 229 Spring 2007 Dr. Markus Lumpe 2 class Sieve { private : Filter* fPrimes; int fMaxNumber; int fLastNumber; public : Sieve( int aNumber ); ~Sieve(); bool nextNumber(); }; The main function is defined as follows: int main() { cout << "The sieve of Eratosthenes: 1000" << endl; Sieve lSieve( 1000 ); // filter all prime numbers while ( lSieve.nextNumber() ); cout << "Done, " << Filter::getNumberOfPrimes() << " primes found!" << endl; } Running the program must produce the following output:
./Eratosthenes The sieve of Eratosthenes: 1000 New prime number found: 2 New prime number found: 3 New prime number found: 5 New prime number found: 7 New prime number found: 11 … New prime number found: 991 New prime number found: 997 Done, 168 primes found! deleting filter for 997 ... deleting filter for 991 ... … deleting filter for 3 ... deleting filter for 2 ... Submission deadline: Thursday, March 8, 2007, 11:00 a.m. Submission procedure: on paper in class.