Java Program to Implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range
Last Updated :
12 Sep, 2022
A number which is divisible by 1 and itself or a number which has factors as 1 and the number itself is called a prime number. The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so.
Example:
Input : from = 1, to = 20
Output: 2 3 5 7 11 13 17 19
Input : from = 4, to = 15
Output: 5 7 11 13
A. Naive approach:
- Define a function named isprime(int n) which will check if a number is prime or not.
- Run a loop from “from” to “to”.
- Inside for loop, check if i is prime, then print the value of i
Below is the implementation of the above approach:
Java
class GFG {
public static boolean isprime( 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 from = 1 , to = 20 , k = 0 ;
for ( int i = from; i <= to; i++)
if (isprime(i))
System.out.print( " " + i);
}
}
|
Output
2 3 5 7 11 13 17 19
Time complexity: O(n3/2)
Auxiliary space: O(1) as it is using constant space for variables
B. Sieve of Eratosthenes:
Initially, assume every number from 0 to n is prime, assign array value of each number as 1. After that, strike off each non-prime number by changing the value from 1 to 0 in an array and finally, print only those numbers whose array value is 1, i.e. prime numbers.
Approach:
- Input n from user
- In array, fill 1 corresponding to each element
- Do a[0]=0 and a[1]=0 as we know 0,1 are not prime
- Assume 1st number(2) to be prime and strike off the multiples of 2(as the multiples of 2 will be non-prime)
- Continue step 3 till square root(n)
- Print the list containing non-striked (or prime) numbers.
Below is the implementation of the above approach:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
int from = 1 , to = 20 , i;
boolean [] a = new boolean [to + 1 ];
Arrays.fill(a, true );
a[ 0 ] = false ;
a[ 1 ] = false ;
for (i = 2 ; i <= Math.sqrt(to); i++)
if (a[i])
for ( int j = i * i; j <= to; j += i) {
a[j] = false ;
}
for (i = from; i <= to; i++) {
if (a[i])
System.out.print( " " + i);
}
}
}
|
Output
2 3 5 7 11 13 17 19
Time Complexity: O(n log(log n))
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...