Department of Computer Science | Institute of Theoretical Computer Science | CADMO

Theory of Combinatorial Algorithms

Prof. Emo Welzl and Prof. Bernd Gärtner

// Program: eratosthenes2.cpp // Calculate prime numbers in {2,...,n-1} using // Eratosthenes' sieve. #include #include // vectors are standard containers with // array functionality int main() { // input std::cout << "Compute prime numbers in {2,...,n-1} for n =? "; unsigned int n; std::cin >> n; // definition and initialization: provides us with // Booleans crossed_out[0],..., crossed_out[n-1], // initialized to false std::vector crossed_out (n, false); // computation and output std::cout << "Prime numbers in {2,...," << n-1 << "}:\n"; for (unsigned int i = 2; i < n; ++i) if (!crossed_out[i]) { // i is prime std::cout << i << " "; // cross out all proper multiples of i for (unsigned int m = 2*i; m < n; m += i) crossed_out[m] = true; } std::cout << "\n"; return 0; }