Primzahl.java
import java.io.*;
public class Primzahl {
public static void main(String[] args) throws IOException {
// bestimmt Primeigenschaft
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
// Zahl erfragen
String s; // String für eingegebene Zeile
System.out.println("Positive ganze Zahl eingeben:");
s = in.readLine();
int zahl = Integer.parseInt(s);
boolean isPrim = true; // bis zum Beweis des Gegenteils
int teiler = 1; // gefundener Teiler
// Eingabe ok
if (zahl <= 0) {
System.out.println("ungültige Eingabe: nicht positiv!");
System.exit(-1);
}
if (zahl == 1) { // Spezialfall 1
isPrim = false;
} else if ((zahl % 2 == 0) && (zahl != 2)) { // durch 2 teilbar
isPrim = false;
teiler = 2;
} else {
int max = (int) Math.floor(Math.sqrt((double) zahl));
for (int i=3; i<=max; i=i+2) {
if (zahl % i == 0) { // durch ungerade Zahl kleiner Wurzel teilbar
isPrim = false;
teiler = i;
}
}
}
// Ausgabe des Ergebnisses
if (isPrim) {
System.out.println(zahl + " ist eine Primzahl");
} else {
System.out.println(zahl + " ist durch " + teiler + " teilbar");
}
}
}