Skip to Content
author's profile photo Miguel Fiúza

CCC2 Getting the longest Collatz Sequence from one million

this.maxSeqLength = 0;
this.bestNumber = 0;
this.limitNumber = 1000000;

function set_max_value(){
  var length;
//Only makes sense to see odd numbers because even numbers will always be even numbers until 1.
//Here we start from the limit number 
  for (var number = this.limitNumber - 1; number >= 3; number = number - 2) {    
    length = getLengthFromSequence(number);
    hasMoreLength(length , number);
  }
}

function getLengthFromSequence(currNumber){
  var length = 1;
  while (currNumber !== 1){
    if((currNumber % 2 == 0) ? (currNumber = currNumber / 2) : (currNumber = 3 * currNumber + 1)); 
    length++;
  }
  return length;
}

function hasMoreLength(length, number){
  if(this.maxSeqLength < length){ this.maxSeqLength = length; this.bestNumber = number;}
}

function getMaxLength(){ return "The Maximinum Sequence Length is: " + this.maxSeqLength; }

function getMaxValue(){ return "The Best Value Under " + this.limitNumber + " is: " + this.bestNumber; }

function getValue_Length(){ return this.getMaxValue() + "\n" + this.getMaxLength(); }

set_max_value();
getValue_Length();

The solution number is 837799 with a chain of 525 numbers.

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

0 Comments

    Add a comment
    10|10000 characters needed characters exceeded