Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package collatz;
- import java.util.ArrayList;
- import java.util.Scanner;
- /**
- *
- * @author Alexander Dierl
- */
- public class Collatz {
- // dynamische Ganzzahl Liste
- private static ArrayList<Long> liste = new ArrayList();
- private static int schritte;
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- // TODO code application logic here
- // zwei zahlen einlesen
- // Variablen definiert
- long zyklenanzahl;
- long maxwert;
- System.out.print("Zyklenanzahl: ");
- zyklenanzahl = einlesen();
- System.out.print("Maxwert: ");
- maxwert = einlesen();
- //berechnung aufrufen
- for (long i = 3; i <= maxwert; i++) {
- collatz(i);
- // Ausgabe aller Listen die bestimmte Zyklenanzahl haben
- // %7d steht für Mindestlaenge, ggfs wird automatisch
- // mit Leerzeichen aufgefuellt, 7 einfach ersetzen fuer mehr oder
- // weniger Leerzeichen
- if (schritte == zyklenanzahl) {
- for (int j = 0; j <= schritte; j++) {
- System.out.printf("%7d ", liste.get(j));
- }
- System.out.println();
- }
- // schritte auf 0 und loesche aktuelle liste
- // um anschließend wieder mit neuem Zykle befuellen zu koennen
- schritte = 0;
- liste.clear();
- }
- }
- public static long einlesen() {
- Scanner scan = new Scanner(System.in);
- if (scan.hasNextLong()) {
- return scan.nextLong();
- } else {
- System.out.print("bitte Eingabe wiederholen mit Ganzzahl(Long): ");
- return einlesen();
- }
- }
- // berechne gerade und ungerade Collatz zahlen
- public static void collatz(long n) {
- // stelle etwas mit allen Zahlen von 2 bis maxwert an
- liste.add(n);
- if (n == 1) {
- ;
- } else if (n % 2 == 0) {
- collatz(n / 2);
- schritte++;
- } else {
- collatz(n * 3 + 1);
- schritte++;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement