Home / Programs / Java Program - Sieve of Eratosthenes
Programming Example

Java Program - Sieve of Eratosthenes

👁 104 Views
💻 Practical Program
📘 Step by Step Learning

An efficient algorithm to find all prime numbers up to a specified integer.

Information & Algorithm

Given Input:


Expected Output:


Program Code

import java.util.Arrays;

public class SieveOfEratosthenes {
    public static void main(String[] args) {
        int n = 50;
        boolean[] prime = new boolean[n + 1];
        Arrays.fill(prime, true);
        prime[0] = prime[1] = false;

        for (int i = 2; i * i <= n; i++) {
            if (prime[i]) {
                for (int j = i * i; j <= n; j += i)
                    prime[j] = false;
            }
        }

        for (int i = 2; i <= n; i++) {
            if (prime[i])
                System.out.print(i + " ");
        }
    }
}

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.