Sieve of Erastosthenes

Normal Implementation (with small optimization)

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] && (long long)i * i <= n) {
        for (int j = i * i; j <= n; j += i)
            is_prime[j] = false;
    }
}

Sieve of Erastosthenes, sieving until root

int n;
vector<bool> is_prime(n+1, true);
is_prime[0] = is_prime[1] = false;
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;
    }
}

Runtime:

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.