Euler’s Sieve is an algorithm that finds all the primes in in time and space.

Hint

This problem can also be solved by the Sieve of Eratosthenes in time and space.

Algorithm

Lemma

For , mark all such that . Applying the lemma yields that is prime iff is unmarked.

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 : primes) {
		if (i * j > n) {
			break;
		}
		f[i * j] = false;
		if (i % j == 0) {
			break;
		}
	}
}
 
return primes;