Sieve of Erastosthenes

Runs in time. Used to compute all Prime Number up to .

Taken from cp-algorithms

int n;
vector<bool> is_prime(n+1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i <= n; i++) {
    if (is_prime[i]) {
        for (int j = i * i; j <= n; j += i)
            is_prime[j] = false;
    }
}

Why are you allowed to start j at i*i?

Because if j wasn’t prime before i*i, it should have already been marked by a smaller j.

  • Ex: consider i = 5. You only need to start at j = 5*5, because any smaller number (5*4, 5*3, 5*2) should have been marked by a previous prime number since those are non-prime.

Segmented Sieve

I ran into this DMOJ problem and it required , which is huge and meant I couldn’t store all of it into the array.

https://www.geeksforgeeks.org/segmented-sieve/ On CP algorithms there is also a solution.