Advertisement
Guest User

Untitled

a guest
Nov 10th, 2015
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package collatz;
  7.  
  8. import java.util.ArrayList;
  9. import java.util.Scanner;
  10.  
  11. /**
  12. *
  13. * @author Alexander Dierl
  14. */
  15. public class Collatz {
  16.  
  17. // dynamische Ganzzahl Liste
  18. private static ArrayList<Long> liste = new ArrayList();
  19. private static int schritte;
  20.  
  21. /**
  22. * @param args the command line arguments
  23. */
  24. public static void main(String[] args) {
  25. // TODO code application logic here
  26. // zwei zahlen einlesen
  27. // Variablen definiert
  28. long zyklenanzahl;
  29. long maxwert;
  30.  
  31. System.out.print("Zyklenanzahl: ");
  32. zyklenanzahl = einlesen();
  33.  
  34. System.out.print("Maxwert: ");
  35. maxwert = einlesen();
  36.  
  37. //berechnung aufrufen
  38. for (long i = 3; i <= maxwert; i++) {
  39. collatz(i);
  40.  
  41. // Ausgabe aller Listen die bestimmte Zyklenanzahl haben
  42. // %7d steht für Mindestlaenge, ggfs wird automatisch
  43. // mit Leerzeichen aufgefuellt, 7 einfach ersetzen fuer mehr oder
  44. // weniger Leerzeichen
  45. if (schritte == zyklenanzahl) {
  46. for (int j = 0; j <= schritte; j++) {
  47. System.out.printf("%7d ", liste.get(j));
  48. }
  49. System.out.println();
  50. }
  51.  
  52. // schritte auf 0 und loesche aktuelle liste
  53. // um anschließend wieder mit neuem Zykle befuellen zu koennen
  54. schritte = 0;
  55. liste.clear();
  56. }
  57. }
  58.  
  59. public static long einlesen() {
  60. Scanner scan = new Scanner(System.in);
  61. if (scan.hasNextLong()) {
  62. return scan.nextLong();
  63. } else {
  64. System.out.print("bitte Eingabe wiederholen mit Ganzzahl(Long): ");
  65. return einlesen();
  66. }
  67. }
  68.  
  69. // berechne gerade und ungerade Collatz zahlen
  70. public static void collatz(long n) {
  71. // stelle etwas mit allen Zahlen von 2 bis maxwert an
  72. liste.add(n);
  73. if (n == 1) {
  74. ;
  75. } else if (n % 2 == 0) {
  76. collatz(n / 2);
  77. schritte++;
  78. } else {
  79. collatz(n * 3 + 1);
  80. schritte++;
  81. }
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement