Prime Sieves
How to find all primes under n? Sieve of Eratosthenes This algorithm is a very intuitive way to find all primes under n. We first create a list of numbers from 2 to n and then iterate over the list. For each number i, we mark all its multiples as non-prime. At the end, all numbers that are not marked are prime. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 vector<int> find_primes(int n) { vector<int> primes; vector<bool> is_prime(n + 1, true); for (int i = 2; i * i <= n; i++) { if (is_prime[i]) { for (int j = i * i; j <= n; j += i) { is_prime[j] = false; } } } for (int i = 2; i <= n; i++) { if (is_prime[i]) { primes.push_back(i); } } return primes; } Let’s analyze the time complexity. For each prime number p, we will iterate from p * p to n. Which means that the time complexity is $\sum_{p \text{ is prime}}^{p \leq n} \frac{n}{p} = n\sum_{p \text{ is prime}}^{p \leq n} \frac{1}{p} = n\log\log n$ (prime harmonic series). ...