The Sieve of Eratosthenes is an algorithm that finds all the primes in in time and space.

Hint

This problem can also be solved by Euler’s Sieve in time and space.

Algorithm

Lemma

For , if is not marked, mark all the multiples of greater than . Applying the lemma yields that is prime iff is unmarked.

This algorithm solves the problem in time and space.

std::vector f(n + 1, true);
std::vector<int> primes;
 
for (int i = 2; i <= n; i++) {
	if (f[i]) {
		primes.push_back(i);
		for (int j = 2 * i; j <= n; j += i) {
			f[j] = false;
		}
	}
}
 
return primes;