Euler’s Sieve is an algorithm that finds the primes in in time and space.
Tip
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.
This algorithm solves the problem in time and space.
std::vector<int> euler(int n) {
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;
}Proof
It is easy to prove that each integer is marked at most once.