Skip to content

Commit a0dfb55

Browse files
committed
Create 014.js
1 parent 0067ee1 commit a0dfb55

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

014.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//accumulator
2+
let longestChainLength = {
3+
number: 0,
4+
length: 0
5+
};
6+
7+
for (let i = 1; i <= 1000000; i++) {
8+
let sequence = [i];
9+
10+
while (sequence[sequence.length - 1] !== 1) { //repeat the Collatz algorithm until we arrive at 1
11+
let lastTerm = sequence[sequence.length - 1];
12+
if (lastTerm % 2 === 0) { //if the last term is even...
13+
sequence.push(lastTerm / 2);
14+
} else { //if the last term is odd...
15+
sequence.push((3 * lastTerm) + 1);
16+
}
17+
}
18+
19+
if (sequence.length > longestChainLength.length) {
20+
longestChainLength.length = sequence.length;
21+
longestChainLength.number = i;
22+
}
23+
}
24+
25+
console.log(longestChainLength.number); //our answer!

0 commit comments

Comments
 (0)