Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
A prime number is a whole number greater than 1, which is only divisible by 1 and itself. The first few prime numbers are 2 3 5 7 11 13 17 19 23. Given a range, L to R, the task is to generate all the prime numbers that exist in the Range.
Examples
Input: 1 10
Output 2 3 5 7
Input: 20 30
Output: 23 29
Approach 1: Check every element whether the element is prime or not.
- Iterate in the Range L to R
- Check every element whether the element is prime or not
- Print the prime numbers in the range
Example
Java
import java.io.*;
class GFG {
static boolean checkPrime( int n)
{
if (n == 1 ) {
return false ;
}
for ( int i = 2 ; i <= Math.sqrt(n); ++i) {
if (n % i == 0 ) {
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
int L = 1 ;
int R = 20 ;
for ( int i = L; i <= R; ++i) {
if (checkPrime(i) == true ) {
System.out.print(i + " " );
}
}
}
}
|
Output
2 3 5 7 11 13 17 19
- Time Complexity: O(n * sqrt(n))
- Space Complexity: O(1)
Approach 2: Using Sieve of Eratosthenes to Generate all the prime numbers
- Generate all the prime numbers using Sieve of Eratosthenes (Refer this article)
- Mark all the multiples of all prime numbers remaining numbers are left Prime numbers
- Till the maximum range of the Value
- Print all the prime numbers in the Given Range
Example
Java
import java.io.*;
class GFG {
static boolean max[] = new boolean [ 1000001 ];
static void fill()
{
int n = 1000000 ;
for ( int i = 2 ; i <= n; ++i) {
max[i] = true ;
}
for ( int i = 2 ; i <= Math.sqrt(n); ++i) {
if (max[i] == true ) {
for ( int j = i * i; j <= n; j += i) {
max[j] = false ;
}
}
}
}
static void range( int L, int R)
{
for ( int i = L; i <= R; ++i) {
if (max[i] == true ) {
System.out.print(i + " " );
}
}
}
public static void main(String[] args)
{
int L = 20 ;
int R = 40 ;
fill();
range(L, R);
}
}
|
Approach 3: Using wheel Sieve to Generate all the Prime numbers. This approach is a very much optimized approach than discussed above approach. In this approach, we use the wheel Factorization method to find the prime numbers in a given range.
Example
Java
import java.util.*;
class GFG {
static boolean isPrime( int N)
{
boolean isPrime = true ;
int [] arr = { 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 };
if (N < 2 ) {
isPrime = false ;
}
if (N % 2 == 0 || N % 3 == 0 || N % 5 == 0 ) {
isPrime = false ;
}
for ( int i = 0 ; i < Math.sqrt(N); i += 30 ) {
for ( int c : arr) {
if (c > Math.sqrt(N)) {
break ;
}
else {
if (N % (c + i) == 0 ) {
isPrime = false ;
break ;
}
}
if (!isPrime)
break ;
}
}
if (isPrime)
return true ;
else
return false ;
}
public static void main(String args[])
{
int L = 10 ;
int R = 20 ;
for ( int i = L; i <= R; ++i) {
if (isPrime(i) == true ) {
System.out.print(i + " " );
}
}
}
}
|
Last Updated :
16 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...