Skip to Content
author's profile photo Miguel Santana

CCC2 The Longest Collatz Sequence Solution

 function longestSequence(n) {
  var maxSeq = 0, maxSeqNum = 0;

  for(var i = n; i > 1; i--) {
    var seqNum = 1; var r = i;

    while (r>1) {seqNum++; r = r % 2 == 1 ? (3*r+1) : r/2;}

    if( seqNum > maxSeq){maxSeq = seqNum; maxSeqNum = i;}
  }

  return "The starting number " + maxSeqNum + " produces the longest chain with " + maxSeq + " terms";
}

console.log(longestSequence(1E6));

the answer is:

"The starting number 837799 produces the longest chain with 525 terms"

* Please Login or Register to Comment on or Follow discussions.

0 Comments

    Add a comment
    10|10000 characters needed characters exceeded