Faktorzerlegung.java

import java.io.*;

public class Faktorzerlegung {
  
  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("ganze Zahl größer 1 eingeben:");
    s = in.readLine();
    int zahl = Integer.parseInt(s);
    
    // Eingabe ok
    if (zahl <= 1) {
      System.out.println("ungültige Eingabe!");
      System.exit(-1);
    }
    
    while (zahl > 1) {
      // Teiler finden und abspalten
      if (zahl % 2 == 0) { // durch 2 teilbar
        System.out.print("2 ");
        zahl /= 2;
      } else {
        boolean isPrim = true;
        int max = (int) Math.floor(Math.sqrt((double) zahl));
        for (int i=3; i<=max; i+=2) {
          if (zahl % i == 0) {  // durch ungerade Zahl kleiner Wurzel teilbar
            System.out.print(i + " ");
            zahl /= i;
            isPrim = false;
            break;   // for-Schleife verlassen
          }
        }
        if (isPrim) {
          System.out.println(zahl);
          zahl = 1;
        }
      }
    }
  }
}