Untitled

mail@pastecode.io avatar
unknown
plain_text
16 days ago
1.1 kB
3
Indexable
Never
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

void simpleSieve(int limit, vector<int>& primes) {
    vector<bool> is_prime(limit + 1, true);
    is_prime[0] = is_prime[1] = false;

    for (int i = 2; i * i <= limit; ++i) {
        if (is_prime[i]) {
            for (int j = i * i; j <= limit; j += i) {
                is_prime[j] = false;
            }
        }
    }

    for (int i = 2; i <= limit; ++i) {
        if (is_prime[i]) {
            primes.push_back(i);
        }
    }
}

void segmentedSieve(int a, int b) {
    int limit = sqrt(b);
    vector<int> primes;
    simpleSieve(limit, primes);

    int n = b - a + 1;
    vector<bool> is_prime(n, true);

    for (int i : primes) {
        int start = max(i * i, (a + i - 1) / i * i);
        for (int j = start; j <= b; j += i) {
            is_prime[j - a] = false;
        }
    }

    for (int i = 0; i < n; ++i) {
        if (is_prime[i] && (i + a) >= 2) {
            cout << i + a << " ";
        }
    }
}

int main() {
    int a, b;
    cin >> a >> b;

    segmentedSieve(a, b);
    return 0;
}
Leave a Comment