Advertisement
m_d16

segmented sieve

Feb 2nd, 2025
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.18 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class SegmentedSieve {
  5.  
  6.     // Function to implement basic Sieve of Eratosthenes for primes up to √R
  7.     public static void simpleSieve(int limit, boolean[] primes) {
  8.         Arrays.fill(primes, true);
  9.         primes[0] = primes[1] = false;
  10.         for (int p = 2; p * p <= limit; p++) {
  11.             if (primes[p]) {
  12.                 for (int i = p * p; i <= limit; i += p) {
  13.                     primes[i] = false;
  14.                 }
  15.             }
  16.         }
  17.     }
  18.  
  19.     // Function to print all prime numbers in the range [L, R] using the segmented sieve approach
  20.     public static void segmentedSieve(int L, int R) {
  21.         // Find all primes up to √R using simple sieve
  22.         int limit = (int) Math.sqrt(R) + 1;
  23.         boolean[] primes = new boolean[limit + 1];
  24.         simpleSieve(limit, primes);
  25.  
  26.         // Create a boolean array for the range [L, R]
  27.         boolean[] isPrime = new boolean[R - L + 1];
  28.         Arrays.fill(isPrime, true);
  29.  
  30.         // Use the primes found to mark non-primes in the range [L, R]
  31.         for (int p = 2; p <= limit; p++) {
  32.             if (primes[p]) {
  33.                 // Find the first multiple of p in the range [L, R]
  34.                 int start = Math.max(p * p, (L + p - 1) / p * p);
  35.  
  36.                 // Mark multiples of p as non-prime in the range [L, R]
  37.                 for (int j = start; j <= R; j += p) {
  38.                     isPrime[j - L] = false;
  39.                 }
  40.             }
  41.         }
  42.  
  43.         // Print all primes in the range [L, R]
  44.         System.out.println("Primes in the range [" + L + ", " + R + "] are:");
  45.         for (int i = 0; i <= R - L; i++) {
  46.             if (isPrime[i]) {
  47.                 System.out.print((i + L) + " ");
  48.             }
  49.         }
  50.         System.out.println();
  51.     }
  52.  
  53.     public static void main(String[] args) {
  54.         Scanner scanner = new Scanner(System.in);
  55.         System.out.print("Enter the range (L R): ");
  56.         int L = scanner.nextInt();
  57.         int R = scanner.nextInt();
  58.         scanner.close();
  59.  
  60.         // Call the segmented sieve function to find primes in the range [L, R]
  61.         segmentedSieve(L, R);
  62.     }
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement