-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path014.js
65 lines (46 loc) · 1.14 KB
/
014.js
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
/**
* Longest Collatz Sequence
* Computes the integer bellow one million that produces the longest chain
*
* Ashen Gunaratne
*
*/
/**
* @function longest
* @summary Computes the longest chain
* @param {Number} ceiling - the starting integer
* @description Returns the integer yielding longest below ceiling + 1
*/
const longest = function computeLongestChain(ceiling) {
let longest = 0;
for (let crest = 0; ceiling !== 0; ceiling--) {
let stage = cycles(ceiling);
if (stage < crest) { continue; }
longest = ceiling;
crest = stage;
}
return longest;
};
/**
* @function cycles
* @summary Computes the number of Collatz sequence terms
* @param {Number} n
* @description Returns the number of terms of the Collatz sequence chain starting at n
*/
const cycles = function computeChainCount(n) {
let length = 1;
// assuming sequence
// eventually reaches 1
while (n !== 1) {
n % 2 !== 0
? n = 3 * n + 1
: n /= 2;
length += 1;
}
return length;
};
// tests
console.assert(cycles(13) === 10, `expected 10 got ${cycles(13)}`);
// answer
console.log(longest(999999));