Prime Sieve Java

import java.util.Arrays;

public class Sieve {
    public static void main(String[] args) {
        int n = 20;

        // 1. Initialize array with values 2 to n
        int[] A = new int[n + 1];
        for (int p = 2; p <= n; p++) {
            A[p] = p;
        }

        // 2. Core Sieve Logic: Iterate up to sqrt(n)
        for (int p = 2; p * p <= n; p++) {
            // 3. If p is not marked, it is a prime
            if (A[p] != 0) {
                // 4. Mark multiples of p starting from p*p as 0 (composite)
                int j = p * p;
                while (j <= n) {
                    A[j] = 0; 
                    j = j + p;
                }
            }
        }

        // 5. Output remaining non-zero elements
        System.out.print("Primes: ");
        for (int i = 2; i <= n; i++) {
            if (A[i] != 0) {
                System.out.print(A[i] + " ");
            }
        }
    }
}

 

import java.util.Arrays;

public class Sieve {
    public static void main(String[] args) {
        int n = 20;

        // 1. Initialize boolean array, default is false in Java
        boolean[] isPrime = new boolean[n + 1];
        Arrays.fill(isPrime, true); // Set all to true initially

        // 2. Core Sieve Logic
        for (int p = 2; p * p <= n; p++) {
            if (isPrime[p]) {
                // 3. Mark multiples as false starting from p*p
                for (int j = p * p; j <= n; j += p) {
                    isPrime[j] = false;
                }
            }
        }

        // 4. Output results
        System.out.print("Primes: ");
        for (int i = 2; i <= n; i++) {
            if (isPrime[i]) {
                System.out.print(i + " ");
            }
        }
    }
}

 

Scroll to Top