Collatz sequence length

1k views Asked by At

I'm trying to find the longest Collatz sequence for numbers less than, say 100, but there's a bug that I can't find, that makes my code crash:

var longest=0; //holds the biggest m
var m=0; //count of steps for at given n

//in the following, the counter var starts the sequence by giving it's
//value to n, then n loops the sequence. When loop finishes as n == 1, new 
//number is looped (n = counter++)

for(var counter = 2; counter <100; counter++){
var n = counter;
while(n!= 1){   //when n==1, loop should stop

            if(n%2 == 0){
                n = even(n);
                m++;
            }
                if(n%2 != 0){   
                n = odd(n);
                m++ ;
            }               
        }   

    if(m>longest){
        longest = m;
    }
    m = 0; // resets m counter of steps in loop for new number to loop
}
function even(k){
    return k/2;
}
function odd(k){
    return 3*k+1;
}

Why is my code crashing?

1

There are 1 answers

2
user2736738 On BEST ANSWER

Instead of counter you should consider using n inside the while loop and also you need to use if-else instead of if-if.

        if(n%2 == 0){
            n = even(n);
            m++;
        }
        else{ 
            n = odd(n);
            m++ ;
        }  

because it is the n that will change in while loop not counter. And you are basically resetting value of n before while loop. So you should check the running value of n.

Collatz sequence simply in each step do perform operation based on it's parity.