Tell us what’s happening:
Hello everyone! Im trying to solve problem number 14 of the Euler Project. We are asked to write a function that takes an integer number n as argument and returns the length of the longest Collatz sequence generated by starters that are stricly lesser t an n.
The Collatz sequence is generated by starting from any positive number and, if the number is even you halve it, otherwise you triple it and then add one. Eventually you will reach one and the sequence is complete.
I tried a recursive approach just to practice recursion but it seems like i’m not getting the results I want. Chat gpt suggest that it’s due to the recursive approach itself, but I wanted to ask the community if that makes sense. If you would like to provide a sanity check on my approach I`d appreciate it a lot.
Thanks in advance and have a good day.
Your code so far
function countCollatz(n){
let counter=0;
function getCollatz(n){
counter++;
if(n==1){
return n;
}
else{
if (!(n%2)){
//console.log(n)
return getCollatz((n/2))
}
else{
//console.log(n)
return getCollatz((3*n+1));
}
}
}
getCollatz(n);
return counter;
}
function longestCollatzSequence(n){
let max=1;
for(let cand=1; cand<n; cand++){
let test=countCollatz(cand);
if(test > max)
max=test;
}
return max;
}
console.log(longestCollatzSequence(5847))
console.log(countCollatz(9));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36
Challenge: Project Euler Problems 1 to 100 - Problem 14: Longest Collatz sequence
Link to the challenge: