-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem14.java
executable file
·36 lines (34 loc) · 1006 Bytes
/
Problem14.java
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
public class HelloWorld{
public static void main(String []args){
System.out.println("Answer: " + collatz(1000000));
}
public static int collatz(int limit) {
long result = 0l;
int maxLength = 0;
int length;
int [] array = new int[limit];
for (int i = 0; i < limit; i++) {
array[i] = -1;
}
array[1] = 1;
for (int i = 2; i < limit; i++) {
result = i;
length = 0;
while (result != 1 && result >= i) {
length++;
if ((result % 2) == 0) {
result/=2;
}
else {
result = 3*result + 1;
}
}
array[i] = length + array[(int)result];
if (array[i] > maxLength) {
maxLength = array[i];
System.out.println(i);
}
}
return maxLength;
}
}