-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathp014.js
More file actions
41 lines (35 loc) · 785 Bytes
/
p014.js
File metadata and controls
41 lines (35 loc) · 785 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
38
39
40
41
var mem = [];
function chainLengthRec(n) {
if (mem[n]) return mem[n];
var result = 1;
if (n == 1) return result;
if (n%2==0) result += chainLengthRec(n/2);
else result += chainLengthRec(3*n+1);
mem[n] = result;
return result;
}
function chainLength(n) {
return chainLengthRec(n, 1);
}
function longestChain(n) {
var longest = 0;
var num = n-1;
for (var i = n-1; i > 0; i--) {
var chain = chainLength(i);
if (chain > longest) {
longest = chain;
num = i;
}
}
return num;
}
test("longestChain", function() {
equal(longestChain(1000000), 837799);
});
test("chainLength", function() {
equal(chainLength(13), 10);
equal(chainLength(2), 2);
equal(chainLength(3), 8);
equal(chainLength(4), 3);
equal(chainLength(5), 6);
});