-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollatz.java
More file actions
97 lines (64 loc) · 1.68 KB
/
Collatz.java
File metadata and controls
97 lines (64 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.util.Random;
import java.util.Scanner;
public class Collatz {
public static void main(String[] Args) {
Collatz c = new Collatz();
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("Enter number: ");
String number = sc.nextLine();
if(number.equals("random")) {
c.operation(new Random().nextInt(100000),1,0);
}
else {
try {
int num = Integer.parseInt(number);
System.out.print("Sequence is: ");
c.operation(num, 1,0);
System.out.println("---------------------");
}catch(Exception e) {
System.out.println("Try an integer next time...");
}
}
}
}
public int operation(int num, int max, int time) {
time++;
if(num == 1) {
System.out.println("1");
System.out.println("Max number is: " + max);
System.out.println("It took "+(time-1)+" moves to fall down to 1.");
return -1;
}
else if(num == 0) {
System.out.println("End");
System.out.println("Max number is: 0");
System.out.println("It took ???"+" moves to fall down to 1.");
return -1;
}
else if(num%2 == 1) {
System.out.print(num + " | ");
if(max < num) {
max = num;
}
return operation(3*num+1, max, time);
}
else {
System.out.print(num + " | ");
if(max < num) {
max = num;
}
return operation(num/2, max, time);
}
}
}
/*
v1.0:
It works
v1.1:
Max number is printed now
v1.2:
NOW WITH TRY-CATCH: It's error proof now! Also I added the random option
v1.3:
Time to fall down to 1 has been added
*/