--- id: 5900f37a1000cf542c50fe8d challengeType: 5 title: 'Problem 14: Longest Collatz sequence' --- ## Description
The following iterative sequence is defined for the set of positive integers:
nn/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under the given limit, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million.
## Instructions
## Tests
```yml tests: - text: longestCollatzSequence(14) should return 9. testString: assert.strictEqual(longestCollatzSequence(14), 9, 'longestCollatzSequence(14) should return 9.'); - text: longestCollatzSequence(5847) should return 3711. testString: assert.strictEqual(longestCollatzSequence(5847), 3711, 'longestCollatzSequence(5847) should return 3711.'); - text: longestCollatzSequence(46500) should return 35655. testString: assert.strictEqual(longestCollatzSequence(46500), 35655, 'longestCollatzSequence(46500) should return 35655.'); - text: longestCollatzSequence(54512) should return 52527. testString: assert.strictEqual(longestCollatzSequence(54512), 52527, 'longestCollatzSequence(54512) should return 52527.'); - text: longestCollatzSequence(1000000) should return 837799. testString: assert.strictEqual(longestCollatzSequence(1000000), 837799, 'longestCollatzSequence(1000000) should return 837799.'); ```
## Challenge Seed
```js function longestCollatzSequence(limit) { // Good luck! return true; } longestCollatzSequence(14); ```
## Solution
```js function longestCollatzSequence(limit) { let longestSequenceLength = 0; let startingNum = 0; function sequenceLength(num) { let length = 1; while (num >= 1) { if (num === 1) { break; } else if (num % 2 === 0) { num = num / 2; length++; } else { num = num * 3 + 1; length++; } } return length; } for (let i = 2; i < limit; i++) { let currSequenceLength = sequenceLength(i); if (currSequenceLength > longestSequenceLength) { longestSequenceLength = currSequenceLength; startingNum = i; } } return startingNum; } ```