2017-08-28 72 views
0

我試圖尋找不到編號的最長Collatz序列,說100,但有,我不能找到一個錯誤,這使得我的代碼崩潰:在Collat​​z序列長度

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

代替計數器,您應該考慮在while循環內使用n,並且還需要使用if-else而不是if-if

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

因爲它是n,它會在while循環中變化而不是counter。而你基本上在while循環之前重置n的值。所以你應該檢查n的運行值。

Collat​​z序列只是在每一步中根據它的奇偶性來執行操作。

+0

謝謝,我剛剛糾正了這一點。它仍然崩潰。 – ahhsad

+0

@ahhsad .:檢查答案... – coderredoc

+0

@ahhsad .:你運行它並明白它出錯了嗎? – coderredoc