58 lines
		
	
	
	
		
			1.8 KiB
		
	
	
	
		
			Java
		
	
	
	
	
	
			
		
		
	
	
			58 lines
		
	
	
	
		
			1.8 KiB
		
	
	
	
		
			Java
		
	
	
	
	
	
import java.util.Arrays;
 | 
						|
import java.util.Scanner;
 | 
						|
 | 
						|
public class SieveOfErathostenes {
 | 
						|
    private static void isValid(String input) {
 | 
						|
        if (input == null) {System.exit(-1);}
 | 
						|
        try {
 | 
						|
            Integer.parseInt(input);
 | 
						|
        } catch (NumberFormatException nfe) {
 | 
						|
            System.out.println("Die eingegebene Zahl ist keine ganze Zahl");
 | 
						|
            System.exit(-1);
 | 
						|
        }
 | 
						|
        int cleanInput = Integer.parseInt(input);
 | 
						|
        if (cleanInput < 2 || cleanInput > 1000) {
 | 
						|
            System.out.println("Die eingegebene Zahl muss mindestens 2 sein und höchstens 1000 sein.");
 | 
						|
            System.exit(-1);
 | 
						|
        }
 | 
						|
    }
 | 
						|
 | 
						|
    private static void printArray(boolean[] arr) {
 | 
						|
        for (int i = 0; i < arr.length; i++) {
 | 
						|
            if (arr[i]) {
 | 
						|
                System.out.printf("%d ", i + 2);
 | 
						|
            }
 | 
						|
        }
 | 
						|
        System.out.printf("%n");
 | 
						|
    }
 | 
						|
 | 
						|
 | 
						|
    public static void main(String[] args) {
 | 
						|
        //System.out.println("Sanity Check");
 | 
						|
        Scanner input_scanner = new Scanner(System.in);
 | 
						|
        System.out.println("Bitte gib eine Zahl ein. ");
 | 
						|
        String user_input = input_scanner.nextLine();
 | 
						|
        input_scanner.close();
 | 
						|
        isValid(user_input);
 | 
						|
        int clean_input = Integer.parseInt(user_input);
 | 
						|
 | 
						|
        boolean[] primes = new boolean[clean_input];
 | 
						|
        Arrays.fill(primes, true);
 | 
						|
 | 
						|
        for (int i = 1; i < clean_input; i++) {
 | 
						|
            if (i == 1) {continue;}
 | 
						|
            if (primes[i]) {
 | 
						|
                for (int j = 2; j < clean_input; j++) {
 | 
						|
                    int tmp = j*i;
 | 
						|
                    if (tmp > clean_input) {
 | 
						|
                        break;
 | 
						|
                    }
 | 
						|
                    primes[tmp - 2] = false;
 | 
						|
                }
 | 
						|
            }
 | 
						|
        }
 | 
						|
 | 
						|
        primes[clean_input - 1] = false;
 | 
						|
        printArray(primes);
 | 
						|
    }
 | 
						|
}
 |