Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Scanner;
- public class SegmentedSieve {
- // Function to implement basic Sieve of Eratosthenes for primes up to √R
- public static void simpleSieve(int limit, boolean[] primes) {
- Arrays.fill(primes, true);
- primes[0] = primes[1] = false;
- for (int p = 2; p * p <= limit; p++) {
- if (primes[p]) {
- for (int i = p * p; i <= limit; i += p) {
- primes[i] = false;
- }
- }
- }
- }
- // Function to print all prime numbers in the range [L, R] using the segmented sieve approach
- public static void segmentedSieve(int L, int R) {
- // Find all primes up to √R using simple sieve
- int limit = (int) Math.sqrt(R) + 1;
- boolean[] primes = new boolean[limit + 1];
- simpleSieve(limit, primes);
- // Create a boolean array for the range [L, R]
- boolean[] isPrime = new boolean[R - L + 1];
- Arrays.fill(isPrime, true);
- // Use the primes found to mark non-primes in the range [L, R]
- for (int p = 2; p <= limit; p++) {
- if (primes[p]) {
- // Find the first multiple of p in the range [L, R]
- int start = Math.max(p * p, (L + p - 1) / p * p);
- // Mark multiples of p as non-prime in the range [L, R]
- for (int j = start; j <= R; j += p) {
- isPrime[j - L] = false;
- }
- }
- }
- // Print all primes in the range [L, R]
- System.out.println("Primes in the range [" + L + ", " + R + "] are:");
- for (int i = 0; i <= R - L; i++) {
- if (isPrime[i]) {
- System.out.print((i + L) + " ");
- }
- }
- System.out.println();
- }
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.print("Enter the range (L R): ");
- int L = scanner.nextInt();
- int R = scanner.nextInt();
- scanner.close();
- // Call the segmented sieve function to find primes in the range [L, R]
- segmentedSieve(L, R);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement