Collat​​z序列长度

时间:2017-08-28 19:40:19

标签: javascript debugging collatz

我试图找到最长的Collatz序列,数字小于100,但有一个我无法找到的错误,这会导致我的代码崩溃:< / p>

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;
}

为什么我的代码会崩溃?

1 个答案:

答案 0 :(得分:1)

您应该考虑在while循环中使用n而不是计数器,而且还需要使用if-else代替if-if

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

因为n会在while循环而非计数器中发生变化。而且你基本上在while循环之前重置n的值。因此,您应该检查n的运行值。

每个步骤中的Collat​​z序列都会根据它的奇偶校验执行操作。