The Wayback Machine - https://web.archive.org/web/20240811013128/https://www.geeksforgeeks.org/java-program-to-implement-sieve-of-eratosthenes-to-generate-prime-numbers-between-given-range/
Open In App

Java Program to Implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range

Last Updated : 12 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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:

  1. Define a function named isprime(int n) which will check if a number is prime or not.
  2. Run a loop from “from” to “to”.
  3. Inside for loop, check if i is prime, then print the value of i

Below is the implementation of the above approach:

Java




// Java Program to Generate Prime
// Numbers Between Given Range
class GFG {
    public static boolean isprime(int n)
    {
        if (n == 1)
            return false;
 
        for (int i = 2; i <= Math.sqrt(n); i++)
 
            // Check if a number has factors
            // its not prime and return 0
            if (n % i == 0)
                return false;
       
        // Check if a number dont
        // have any factore
        // its prime and return 1
        return true;
    }
    public static void main(String[] args)
    {
         
        // Suppose we want to print
        // prime no.  from 1 to 20
        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: 

  1. Input n from user
  2. In array, fill 1 corresponding to each element
  3. Do a[0]=0 and a[1]=0 as we know 0,1 are not prime
  4. Assume 1st number(2) to be prime and strike off the multiples of 2(as the multiples of 2 will be non-prime)
  5. Continue step 3 till square root(n)
  6. Print the list containing non-striked (or prime) numbers.

Below is the implementation of the above approach: 

Java




// Java Program to Implement
// Sieve of eratosthenes
// to Generate Prime Numbers
// Between Given Range
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);
 
        // 0 and 1 are not prime
        a[0] = false;
        a[1] = false;
        for (i = 2; i <= Math.sqrt(to); i++)
 
            // Check if number is prime
            if (a[i])
                for (int j = i * i; j <= to; j += i) {
                    a[j] = false;
                }
        for (i = from; i <= to; i++) {
 
            // Printing only prime numbers
            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)



Previous Article
Next Article

Similar Reads

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 ele
5 min read
Java Program for Sieve of Eratosthenes
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For example, if n is 10, the output should be "2, 3, 5, 7". If n is 20, the output should be "2, 3, 5, 7, 11, 13, 17, 19". Java Code // Java program to print all primes smaller than or equal to // n using Sieve of Eratosthenes class SieveOfErat
2 min read
Java Program to Maximize difference between sum of prime and non-prime array elements by left shifting of digits minimum number of times
Given an array arr[] of size N, the task is to find the maximum difference between the sum of the prime numbers and the sum of the non-prime numbers present in the array, by left shifting the digits of array elements by 1 minimum number of times.  Examples: Input: arr[] = {541, 763, 321, 716, 143}Output: Difference = 631, Count of operations = 6Exp
5 min read
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Schonhage-Strassen algorithm is one of the fastest ways of multiplying very large integer values (30000 to 150000 decimal digits). This algorithm was developed by Arnold Schönhage and Volker Strassen. Though the Furer's algorithm is faster than that of Schonhage-Strassen's algorithm, there are no practical applications for it, except Galactic algor
3 min read
Check if a number is Prime, Semi-Prime or Composite for very large numbers
Given a very large number N (&gt; 150), the task is to check whether this number is Prime, Semi-Prime or Composite.Example: Input: N = 90000000 Output: Not Prime Explanation: we have (N-1)%6 = 89999999%6 = 1 and (N+1)%6 = 90000001%6 = 5 Since n-1 and n+1 is not divisible by 6 Therefore N = 90000000 is Not PrimeInput: N = 7894561 Output: Semi-Prime
8 min read
Java Program to Generate Random Numbers Using Multiply with Carry Method
In computer science, multiply-with-carry (MWC) is a method invented by George Marsaglia for generating sequences of random integers based on an initial set from two to many thousands of randomly chosen seed values. The main advantage of the MWC method is that it invokes simple computer integer arithmetic and leads to the very fast generation of seq
2 min read
How do I generate random integers within a specific range in Java?
Given two numbers Min and Max, the task is to generate a random integer within this specific range in Java. Examples: Input: Min = 1, Max = 100 Output: 89 Input: Min = 100, Max = 899 Output: 514 Approach: Get the Min and Max which are the specified range. Call the nextInt() method of ThreadLocalRandom class (java.util.concurrent.ThreadLocalRandom)
1 min read
Java Program to Implement Control Table in Java
Control tables will be tables that control the control stream or have a significant influence on program control. There are no unbending guidelines about the structure or substance of a control table—its passing trait is its capacity to coordinate the control stream somehow or another through "execution" by a processor or mediator. The plan of such
3 min read
Quick ways to check for Prime and find next Prime in Java
Many programming contest problems are somehow related Prime Numbers. Either we are required to check Prime Numbers, or we are asked to perform certain functions for all prime number between 1 to N. Example: Calculate the sum of all prime numbers between 1 and 1000000. Java provides two function under java.math.BigInteger to deal with Prime Numbers.
2 min read
Java Program to Create a Matrix and Fill it with Prime Numbers
Prime Numbers are the number which can be divisible by only 1 and itself, it cannot be divisible by any other number. The task here is to find the prime numbers and store them in the form of a matrix. Example: Prime numbers are: 2, 3, 5, 7 Output: 2 3 5 7 Prime numbers : 2, 3, 5, 7, 9, 11, 13, 17, 19 Output: 2 3 5 7 9 11 13 17 19 Approach: First, t
3 min read
three90RightbarBannerImg