Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range


The naïve approach to finding the prime numbers in the given range is to check whether each number is prime. Also, we need to make iterations equal to the given number to check whether the number is prime. So, the naïve approach is very time-consuming, and we need to optimize it to make it time efficient.

In this tutorial, we will learn wheel factorization and Sieve of Eratosthenes algorithms given by Sieve to find the prime numbers in the given range efficiently.

Problem statement − We have given left and right integer values. We need to implement the Wheel factorization and Sieve of Eratosthenes algorithm to find the prime numbers in the given range.

Sample Examples

Input

left = 10;  right = 50;

Output

11 13 17 19 23 29 31 37 41 43 47

Explanation

It prints the prime numbers between 10 and 50.

Input

left = 9;  right = 10;

Output

“”

Explanation

It prints an empty string as there is no prime numbers between 9 and 10.

Input

left = 144; right = 200;

Output

149 151 157 163 167 173 179 181 191 193 197 199

Approach 1

In this approach, we will use the Sieve of Eratosthenes algorithm to find prime numbers between two given numbers.

In the Sieve of Eratosthenes algorithm, we use an array of length N to store Boolean value according to whether the number is prime. We store false for even numbers as they are non-prime. After that, we visit each unmarked number and change the Boolean value from true to false for its multiple.

Algorithm

  • Step 1 − Define the numbers[] array to store the boolean value according to the number is prime.

  • Step 2 − Execute the createMatrix() function to find prime numbers between 1 to 10,000,000 and update the numbers[] array.

  • Step 3 − Start traversing from 4 to the given range. If the index is even, initialize the numbers[p] with false. Otherwise, with true.

  • Step 4 − Use the loop to make iterations from 3 to the given range. If number [p] is true, mark all multiples of the number as false.

  • Step 5 − Execute the getPrimes() function to get all primes numbers between left and right.

  • Step 5.1 − n the getPrimes() function, traverse the array in the given range, and print the index value if the array element is true.

Example

import java.io.*;

public class Main {
   // Maximum range
   static boolean numbers[] = new boolean[1000001];
   static void createMatrix() {
      // max range
      int range = 1000000;
      // Initially mark even numbers as non-prime and odd numbers as prime
      for (int p = 4; p <= range; ++p) {
         if (p % 2 == 0)
            numbers[p] = false;
         else
            numbers[p] = true;
      }
      // Traverse all odd numbers and update if the number is not prime
      for (int p = 3; p <= Math.sqrt(range); p += 2) {
         // If the number is prime
         if (numbers[p] == true) {
            // Update all multiples of p as non-prime
            for (int q = p * p; q <= range; q += p) {
               numbers[q] = false;
            }
         }
      }
   }
   static void getPrimes (int left, int right) {
      System.out.println("Prime numbers in the given range are:");
      for (int p = left; p <= right; ++p) {
         // Printing prime numbers in the range
         if (numbers[p] == true) {
            System.out.print(p + " ");
         }
      }
   }
   public static void main(String[] args) {
      int left = 10;
      int right = 50;
      createMatrix();
      // Get prime numbers in the given range
      getPrimes(left, right);
   }
}

Output

Prime numbers in the given range are:
11 13 15 17 19 21 23 27 29 31 33 37 39 41 43 47

Time complexity – O(N*logN), where O(N) is to traverse the array, and O(logN) is to mark all multiples as false.

Approach 2

In this approach, we need to take the base list of prime numbers. Here, we will use the {2, 3, 5}. After that, we need to decide the wheel size after multiplying all the prime numbers of the base list. So, our wheel size will be ( 2*3*5 ) 30.

In the next step, we need to take all prime numbers from 1 to wheel size to make a wheel of it. We will take { 7, 11, 13, 17, 19, 23, 29, 31 } as we already included 2, 3, and 5 in the base list.

So, the wheel contains a layer of 30 numbers. In each layer, we check if the number is divisible by any minimum integer to ensure whether the number is prime.

Algorithm

  • Step 1 − Initialize the ‘isNumPrime´ with true, assuming the number is prime.

  • Step 2 − Also, Initialize the primes array with prime numbers of the first layer of the wheel.

  • Step 3 − If the number is less than 2, update ‘isNumPrime’ with false.

  • Step 4 − If the number is divisible by 2, 3, or 5, update ‘isNumPrime’ with false.

  • Step 5 − se the loop to make iterations from 0 to sqrt(Number) in step 30, as each layer of a wheel contains 30 numbers.

  • Step 6 − Use a nested loop to traverse all prime numbers of the first layer. If the prime number of the first layer is greater than sqrt(num), break the nested loop.

  • Step 7 − Otherwise, if the number is divisible by a prime number of the first layer + p (multiple of 30), update ‘isNumPrime’ with false and break the nested loop.

  • Step 8 − In the outer loop, if the value of the‘isNumPrime’ is false, break the outer loop.

  • Step 9 − Return the value of the ‘isNumPrime’ variable.

Example

In this example, we traverse each number in the given range and check whether it is prime using the wheel factorization algorithm.

import java.util.*;

public class Main {
   static boolean checkForPrime(int num) {
      boolean isNumPrime = true;
      // Wheel of prime numbers
      int[] primes = { 7, 11, 13, 17, 19, 23, 29, 31 };
      // Base Case
      if (num < 2) {
         isNumPrime = false;
      }
      if (num % 2 == 0 || num % 3 == 0 || num % 5 == 0) {
         isNumPrime = false;
      }
      // Check in the wheel P is the layer of the wheel
      for (int p = 0; p < Math.sqrt(num); p += 30) {
         // Check for the list of Sieve in primes[]
         for (int pm : primes) {
            // When the prime number exceeds the square root of the num
            if (pm > Math.sqrt(num)) {
               break;
            }
            // If num is multiple of pm in the current wheel
            else {
               if (num % (pm + p) == 0) {
                  isNumPrime = false;
                  break;
               }
            }
            // When a number is non-prime in the current layer
            if (!isNumPrime)
               break;
         }
      }
      return isNumPrime;
   }
   public static void main(String args[]) {
      int left = 10;
      int right = 50;
      System.out.println("Prime numbers in the given range are :");
      for (int p = left; p <= right; ++p) {
         if (checkForPrime(p) == true) {
            System.out.print(p + " ");
         }
      }
   }
}

Output

Prime numbers in the given range are:
11 13 17 19 23 29 31 37 41 43 47

Time complexity – O(N*N1/2)

Space complexity – O(1)

The Sieve of Eratosthenes algorithm is only used when we need to find the prime number in a particular range, but the Wheel factorization algorithm is used to find all prime numbers in the large range.

Updated on: 04-Jul-2023

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements