Sieve of Eratosthenes [prime max]

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 4 Exercise 14
Using std_lib_facilities.h by Bjarne Stroustrup.

//	Philipp Siedler
//	Bjarne Stroustrup's PP
//	Chapter 4 Exercise 14

#include "std_lib_facilities.h"
#include "math.h"

int main()
try
{
	int max = 100;
	string s;
	vector<int> seriesNum;

	cout << "Enter a maximum value for the prime number generator: \n";
	if (cin >> max){}
	else {
		cin.clear();
		cin >> s;
		error("Bad input for maximum", s);
	}

	//fill series of numbers
	for (int i = 2; i < max; i++) {
		seriesNum.push_back(i);
	}

	//check for primes
	for (int j = 2; j < 6; j++) {
		for (int i = 0; i < seriesNum.size(); i++) {
			if (seriesNum[i] % j == 0 && seriesNum[i] != j) {
				seriesNum[i] = 0;
			}
		}
	}

	//print primes
	for (int i = 0; i < seriesNum.size(); i++) {
		if (seriesNum[i] != 0) {
			cout << seriesNum[i] << "\n";
		}
	}

	keep_window_open(".");
}

catch (runtime_error e) {
	cout << e.what() << "\n";
	keep_window_open(".");
}
catch (...) {
	cout << "Exiting.\n";
	keep_window_open(".");
}
Output:
Enter a maximum value for the prime number generator:
25
2
3
5
7
11
13
17
19
23
Please enter . to exit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.