Compiled and tested here: http://www.browxy.com/
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.println("Enter a number: "); int N = reader.nextInt(); // user input. // Array // 0 - prime, 1 - composite int[] arr = new int[N + 1]; arr[0] = arr[1] = 1; // loop from 2 to square root of N for (int i = 2; i <= Math.sqrt(N); i++) { // check if prime if (arr[i] == 0) { // add all factors of i to composite numbers to N for (int j = i * i; j <= N; j += i) { arr[j] = 1; } } } // Print all positions for which fields are not reset for (int i = 0; i < arr.length; i++) { if (arr[i] == 0) { System.out.print(i + ", "); } } } }