-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEuler14.java
47 lines (39 loc) · 969 Bytes
/
Euler14.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
37
38
39
40
41
42
43
44
45
46
47
package Euler;
import java.util.LinkedList;
public class Euler14 {
static final short[] cache = new short[1000000];
public static int CollazSum(long n){
if(n == 1) return 1;
if(n < cache.length){
int count = cache[((int) n)];
if(count > 0){
return count;
}
}
int next = (n & 1) == 0
? 1 + CollazSum(n >> 1)
: 2 + CollazSum((n * 3 + 1) >> 1);
if(n < cache.length)
cache[((int) n)] = (short) next;
return next;
}
static{
for(int i = 10; i < cache.length; i *= 2)
CollazSum(i - 1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
long start = System.currentTimeMillis();
int len = 0, res = 0;
for(int i = 1; i < 1000000; i++){
int maxCount = CollazSum(i);
if(maxCount > len){
len = maxCount;
res = i;
}
}
long end = System.currentTimeMillis();
System.out.println(res+ " with chain size of "+len);
System.out.println(end - start +" ms");
}
}