Tell us what’s happening:
I am trying to use a helper function to calculate the length of the chain then outside of the helper function use a for loop to decrement the variable count and assign a variable max to count if count is larger than max. I am having trouble getting it work though, can anyone help me find the flaws in my code? It now works for the first 2 tests and that makes it difficult to troubleshoot. I do not understand why it would pass the first 2 and not the last 3.
Your code so far
function longestCollatzSequence(limit) {
let max = 0
let maxLim
function lengthOfChain(limit){
let arr = [limit]
while(limit !== 1){
limit % 2 === 0 ? limit = limit / 2 : limit = 3*limit + 1
// console.log(limit)
arr.push(limit)
}
//console.log(arr)
if(limit === 1){
return arr.length
}
}
//console.log(lengthOfChain(14))
for(let i = limit; i> 0; i--){
if(lengthOfChain(i)> max){
max = lengthOfChain(i)
maxLim = i
}
// console.log(max)
console.log("this is where the max length was")
console.log(maxLim)
}
return maxLim
}
console.log(longestCollatzSequence(14));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36
.
Challenge: Problem 14: Longest Collatz sequence
Link to the challenge:
https://www.freecodecamp.org/learn/coding-interview-prep/project-euler/problem-14-longest-collatz-sequence