-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp014.java
More file actions
37 lines (30 loc) · 829 Bytes
/
p014.java
File metadata and controls
37 lines (30 loc) · 829 Bytes
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
package level01;
import java.util.Map;
import org.junit.Test;
import lib.EulerTest;
public class p014 extends EulerTest {
final int N = 1000000;
/**
* Find the natural number under N that generates the longest Collatz chain.
*/
@Test
public void test() {
int maxChainLen = 0;
Map<Long, Integer> cache = map(1L, 1);
for (long i : range(1, N)) {
long n = i;
int chainLen = 0;
while (!cache.containsKey(n)) {
chainLen++;
n = n % 2 == 0 ? n / 2 : 3 * n + 1;
}
chainLen += cache.get(n);
cache.put(i, chainLen);
if (chainLen > maxChainLen) {
maxChainLen = chainLen;
ans = i;
}
}
check(837799);
}
}