Skip to Content
author's profile photo Renato Rodrigues

CCC2 - Longest Collatz sequence problem

// Calculates from a given number how many sequence has
function sequenceFn(number) {
  var sequenceNumber = 1;
  while(number > 1) {
    number = ((number % 2 == 0) ? number/2 : 3*number+1);
    sequenceNumber++;
  }
  return sequenceNumber; 
}

// Calculates from a given starting number to 1, 
// what number has the longest chain
function main(number) {
  var maxSequence = 0, maxNumber = 0;

  for(var i = number; i > 1; i--) {
    sequenceNo = sequenceFn(i);
    if(sequenceNo > maxSequence) {
      maxSequence = sequenceNo;
      maxNumber = i;
    }
  }

  return "Number " + maxNumber + 
   " produces the longest chain (" + maxSequence + ")";
}

console.log(main(999999));

The answer is "Number 837799 produces the longest chain (525)"

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

0 Comments

    Add a comment
    10|10000 characters needed characters exceeded