Skip to the content of the web site.

Project H.1.b: Sieve of Eratosthenes

For this project, you will have to additionally know how to dyamically allocate arrays.

Write a function with the declaration

bool *flag_primes( unsigned long n );

which dynamically allocates a Boolean-valued array of capacity $n + 1$ and returns that array so that array[k] == true if k is prime, and array[k] == false if k is composite.

You can test your code with

#include <iostream>

// Function declarations
bool *flag_primes( unsigned long n );
int main();

// Function definitions
int main() {
	for ( unsigned long k{10}; k <= 80; k += 10 ) {
		bool *primes{ flag_primes( k ) };

		std::cout << "2";

		for ( unsigned long j{3}; j <= k; ++j ) {
			if ( primes[j] ) {
				std::cout << ", " << j;
			}
		}

		std::cout << std::endl;

		delete[] primes;
		primes = nullptr;
	}

	return 0;
}

// Your code here;

The output should be

2, 3, 5, 7
2, 3, 5, 7, 11, 13, 17, 19
2, 3, 5, 7, 11, 13, 17, 19, 23, 29
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79