The Wayback Machine - https://web.archive.org/web/20250203120036/https://www.geeksforgeeks.org/java-program-for-sieve-of-eratosthenes/
Open In App

Java Program for Sieve of Eratosthenes

Last Updated : 05 May, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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




// Java program to print all primes smaller than or equal to
// n using Sieve of Eratosthenes
 
class SieveOfEratosthenes
{
    void sieveOfEratosthenes(int n)
    {
        // Create a boolean array "prime[0..n]" and initialize
        // all entries it as true. A value in prime[i] will
        // finally be false if i is Not a prime, else true.
        boolean prime[] = new boolean[n+1];
        for(int i=0;i<=n;i++)
            prime[i] = true;
         
        for(int p = 2; p*p <=n; p++)
        {
            // If prime[p] is not changed, then it is a prime
            if(prime[p] == true)
            {
                // Update all multiples of p
                for(int i = p*p; i <= n; i += p)
                    prime[i] = false;
            }
        }
         
        // Print all prime numbers
        for(int i = 2; i <= n; i++)
        {
            if(prime[i] == true)
                System.out.print(i + " ");
        }
    }
     
    // Driver Program to test above function
    public static void main(String args[])
    {
        int n = 30;
        System.out.print("Following are the prime numbers ");
        System.out.println("smaller than or equal to " + n);
        SieveOfEratosthenes g = new SieveOfEratosthenes();
        g.sieveOfEratosthenes(n);
    }
}
 
// This code has been contributed by Amit Khandelwal.


Output

Following are the prime numbers smaller than or equal to 29
2 3 5 7 11 13 17 19 23 29 

Please refer complete article on Sieve of Eratosthenes for more details!
 


Master JAVA and also get 90% fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.

After successfully processing refunds worth over INR 5 Cr, GeeksforGeeks is back with the Three 90 challenge and this is your chance to upskill and get 90% refund. What more motivation do you need? Start the challenge right away!


Next Article
Article Tags :

Similar Reads

Java Program to Implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range
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
3 min read
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 Program to calculate volume of a Tetrahedron
A Tetrahedron is simply a pyramid with a triangular base. It is a solid object with four triangular faces, three on the sides or lateral faces, one on the bottom of the base and four vertices or corners. If the faces are all congruent equilateral triangles, then the tetrahedron is called regular. The volume of the tetrahedron can be found by using
1 min read
Java Program for Program to find area of a circle
Area of a circle can simply be evaluated using following formula. Area = pi * r2 where r is radius of circle Java Code // Java program to find area // of circle class Test { static final double PI = Math.PI; static double findArea(int r) { return PI * Math.pow(r, 2); } // Driver method public static void main(String[] args) { System.out.println(
1 min read
Java Program for Program to cyclically rotate an array by one
Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4}Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Java Code import java.util.Arrays; public class Test { static int arr[] = new int[]{1, 2, 3, 4, 5}; // Method for rotation static vo
1 min read
Java Program to Extract Content from a Java's .class File
In this article, we are going to extract the contents of the Java class file using the Apache Tika library. Apache Tika is used for document type detection and content extraction from various file formats. It uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing
2 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
Java Program to Empty an ArrayList in Java
ArrayList class is a resizable array, present in 'java.util package'. The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an Arra
3 min read
How to Convert java.sql.Date to java.util.Date in Java?
If we have the Date object of the SQL package, then we can easily convert it into an util Date object. We need to pass the getTime() method while creating the util Date object. java.util.Date utilDate = new java.util.Date(sqlDate.getTime()); It will give us util Date object. getTime() method Syntax: public long getTime() Parameters: The function do
1 min read
Different Ways to Convert java.util.Date to java.time.LocalDate in Java
Prior to Java 8 for handling time and dates we had Date, Calendar, TimeStamp (java.util) but there were several performance issues as well as some methods and classes were deprecated, so Java 8 introduced some new concepts Date and Time APIs' (also known as Joda time APIs') present in java.time package. Java 7: Date, Calendar, TimeStamp present ins
3 min read
How to Convert java.util.Date to java.sql.Date in Java?
Date class is present in both java.util package and java.sql package. Though the name of the class is the same for both packages, their utilities are different. Date class of java.util package is required when data is required in a java application to do any computation or for other various things, while Date class of java.sql package is used whene
3 min read
Java Program for Radix Sort
The Radix Sort Algorithm Do the following for each digit i where i varies from the least significant digit to the most significant digit.Sort input array using counting sort (or any stable sort) according to the ith digit. C/C++ Code // Radix sort Java implementation import java.io.*; import java.util.*; class Radix { // A utility function to get m
3 min read
Java Program for n-th Fibonacci numbers
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2with seed values F0 = 0 and F1 = 1.Method 1 ( Use recursion ) Java Code // Fibonacci Series using Recursion class Fibonacci { static int fib(int n) { if (n==0) return 0; else if(n==1 || n==2) return 1; return fib(n - 1) + fib(n - 2); }
4 min read
Java Program for Counting Sort
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Java Code // Java implementation of Counting Sort import java.io.*; public class CountingSor
2 min read
Java Program for ShellSort
In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h'th element is sorted. Java Code // Java implementation of ShellSort class ShellSort { /* An utility function to print array of size n*/ static void printArray(int arr[]) { in
2 min read
Java Program for Longest Common Subsequence
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, "abc", "abg", "bdf", "aeg", '"acefg", .. etc are subsequences of "abcdefg". So a string of length n has 2^n different possible s
4 min read
Java Program for Binary Search (Recursive and Iterative)
So as we all know binary search is one of the searching algorithms that is most frequently applied while dealing with data structures where the eccentric goal is not to traverse the whole array. Here array must be sorted as we check the middle element and ignore the half of the array which is of no use as per the number system. We basically ignore
4 min read
Java Program for Min Cost Path
Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination). You can only
3 min read
Java Program for Longest Increasing Subsequence
The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. More Examples: Input : arr[] = {3, 10, 2, 1,
5 min read
Java Program for GCD of more than two (or array) numbers
The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers. gcd(a, b, c) = gcd(a, gcd(b, c)) = gcd(gcd(a, b), c) = gcd(gcd(a, c), b) Java Code // Java program to find GCD of two or // more numbers public class GCD { // Function t
1 min read
Java Program for Common Divisors of Two Numbers
Given two integer numbers, the task is to find the count of all common divisors of given numbers? Input : a = 12, b = 24 Output: 6 // all common divisors are 1, 2, 3, // 4, 6 and 12 Input : a = 3, b = 17 Output: 1 // all common divisors are 1 Input : a = 20, b = 36 Output: 3 // all common divisors are 1, 2, 4 Java Code // Java implementation of pro
2 min read
Java Program for Bitonic Sort
Bitonic Sequence is a sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that x0 <= x1 …..<= xi and xi >= xi+1….. >= xn-1 A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty
4 min read
Java Program for Bitonic Sort
Bitonic Sequence: A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that x0 <= x1 …..<= xi and xi >= xi+1….. >= xn-1 A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty.
4 min read
Java Program for Recursive Bubble Sort
Background :Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.Following is iterative Bubble sort algorithm : // Iterative Bubble Sort bubbleSort(arr[], n) { for (i = 0; i < n-1; i++) // Last i elements are already in place for (j = 0; j arr[j+1]) swap(arr[j], arr[j+1]
2 min read
Java Program for BogoSort or Permutation Sort
BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted.(Wiki) For example, if bogosort is used to sort a deck of cards, it would consist o
2 min read
Java Program for Recursive Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.Below is an iterative algorithm for insertion sort Algorithm // Sort an arr[] of size n insertionSort(arr, n) Loop from i = 1 to n-1. a) Pick element arr[i] and insert it into sorted sequence arr[0..i-1] Java Code // Recursive Java program for inserti
2 min read
Java Program for Gnome Sort
Algorithm Steps If you are at the start of the array then go to the right element (from arr[0] to arr[1]).If the current array element is larger or equal to the previous array element then go one step right if (arr[i] >= arr[i-1]) i++;If the current array element is smaller than the previous array element then swap these two elements and go one
2 min read
Java Program for Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort that uses last element as pivot. Java Code // Recursive Java Program for merge sort import java.util.Arrays; public class GFG { public static void mergeSort(int[] array) { if(array == null) { return; } if(array.length &gt; 1) { int mid = array.length / 2; // Split left part int[] lef
2 min read
Java Program for nth multiple of a number in Fibonacci Series
Given two integers n and k. Find position the n'th multiple of K in the Fibonacci series. Examples: Input : k = 2, n = 3 Output : 9 3'rd multiple of 2 in Fibonacci Series is 34 which appears at position 9. Input : k = 4, n = 5 Output : 30 5'th multiple of 5 in Fibonacci Series is 832040 which appears at position 30. An Efficient Solution is based o
4 min read
Java Program for Zeckendorf\'s Theorem (Non-Neighbouring Fibonacci Representation)
Given a number, find a representation of number as sum of non-consecutive Fibonacci numbers. Examples: Input: n = 10 Output: 8 2 8 and 2 are two non-consecutive Fibonacci Numbers and sum of them is 10. Input: n = 30 Output: 21 8 1 21, 8 and 1 are non-consecutive Fibonacci Numbers and sum of them is 30. The idea is to use Greedy Algorithm. 1) Let n
2 min read