Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Basics

Primes in a Range (Segmented Sieve)

Medium · Basics · Asked at Amazon, Microsoft, Codenation

Print every prime number p with L ≤ p ≤ R, in increasing order, separated by spaces. If there is none, print -1.

R can be as large as 10^12, so testing each number one by one is too slow — but the range itself is short.

Input

A single line with L and R.

Output

The primes in [L, R] separated by spaces, or -1.

Constraints

Sieve the primes up to √R (at most 10^6) first. Then, for each such prime p, cross out its multiples inside [L, R], starting from max(p × p, the first multiple ≥ L).

Example 1

Input

10 30

Output

11 13 17 19 23 29

Example 2

Input

24 28

Output

-1

Hints

  1. A composite number x ≤ R has a prime factor ≤ √R ≤ 10^6.
  2. Sieve the primes up to √R with the normal Sieve of Eratosthenes.
  3. Use each of them to cross out its multiples inside [L, R] only.

Approach

Make a boolean array for the window [L, R] (at most 10^5 + 1 cells). For every prime p ≤ √R, the first multiple to cross out is max(p², ⌈L/p⌉ × p) — starting at p² keeps p itself unmarked when it lies inside the range. Whatever is left unmarked (and ≥ 2, since 1 is not prime) is prime. Index the window by x − L so the huge values never become array indices.

Complexity: O(√R log log R + (R − L) log log R) time · O(√R + (R − L)) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    long long L, R;
    cin >> L >> R;
    long long lim = (long long) sqrtl((long double) R) + 1;
    vector<bool> composite(lim + 1, false);
    vector<long long> primes;
    for (long long i = 2; i <= lim; i++) {
        if (composite[i]) continue;
        primes.push_back(i);
        for (long long j = i * i; j <= lim; j += i) composite[j] = true;
    }
    vector<bool> marked(R - L + 1, false);
    for (long long p : primes) {
        long long start = max(p * p, (L + p - 1) / p * p);
        for (long long x = start; x <= R; x += p) marked[x - L] = true;
    }
    string out;
    for (long long x = L; x <= R; x++)
        if (x >= 2 && !marked[x - L]) out += to_string(x) + " ";
    if (out.empty()) cout << -1 << "\n";
    else {
        out.pop_back();
        cout << out << "\n";
    }
    return 0;
}

Python solution

import math

L, R = map(int, input().split())
lim = math.isqrt(R) + 1
is_prime = bytearray([1]) * (lim + 1)
is_prime[0] = is_prime[1] = 0
for i in range(2, math.isqrt(lim) + 1):
    if is_prime[i]:
        is_prime[i * i :: i] = bytearray(len(range(i * i, lim + 1, i)))

seg = bytearray([1]) * (R - L + 1)
for p in range(2, lim + 1):
    if is_prime[p]:
        start = max(p * p, (L + p - 1) // p * p)
        if start <= R:
            seg[start - L :: p] = bytearray(len(range(start - L, R - L + 1, p)))

res = [str(L + i) for i in range(R - L + 1) if seg[i] and L + i >= 2]
print(" ".join(res) if res else -1)

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long L = sc.nextLong(), R = sc.nextLong();
        int lim = (int) Math.sqrt((double) R) + 1;
        boolean[] composite = new boolean[lim + 1];
        List<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= lim; i++) {
            if (composite[i]) continue;
            primes.add(i);
            for (long j = (long) i * i; j <= lim; j += i) composite[(int) j] = true;
        }
        boolean[] marked = new boolean[(int) (R - L + 1)];
        for (int p : primes) {
            long start = Math.max((long) p * p, (L + p - 1) / p * p);
            for (long x = start; x <= R; x += p) marked[(int) (x - L)] = true;
        }
        StringBuilder sb = new StringBuilder();
        for (long x = L; x <= R; x++)
            if (x >= 2 && !marked[(int) (x - L)]) sb.append(x).append(' ');
        System.out.println(sb.length() == 0 ? "-1" : sb.toString().trim());
    }
}

Solve Primes in a Range (Segmented Sieve) online · All practice problems