Skip to Content
author's profile photo senthil Kumar Balaguru

CCC2 : Longest Collatz sequence Challange

// Constant for Maximum Sequence Starting number
const maxStartNumber = 1000000;
// Create Array to store terms to refer 
let termsArray = Array.from({length: maxStartNumber+1}, (v, i) => -1);

// Main function to calculate number with longest terms
function getLongestStartNumber(maxvalue) 
{
  let longestStartNumber;
  let maxTerm = 1;
  let currentTerm;

  for (let i = 1; i < maxvalue; i++)  {
// get the number of terms     
   currentTerm = getTerms(i);
    termsArray[i] = currentTerm;
    if (maxTerm < currentTerm) {
      maxTerm = currentTerm;
      longestStartNumber = i;
    }
  
  }
  return longestStartNumber;
}

// check the number is odd or even
function isEven(num) {
  if (num % 2 == 0) {
    return true; // Even Number
  }
  else {
    return false; // Odd Number
  }

}

// get the CollatzSequence  terms for the given number
function getTerms(num) {
  let terms = 1;
  do {
        if ( termsArray[num] == -1 || num > ( termsArray.length -1 ) )
     {
       ++terms; 
     }
     else
     {
        terms = terms + ( termsArray[num] - 1 ) ;
      break;
      
     }

    
    if (isEven(num)) {
      num = num / 2;
    }
    else {
      num = (3 * num) + 1;
    }

  } while (num != 1);

   return terms;
}
// Print the Result
alert(`The longest starting number under one million is , ${getLongestStartNumber(maxStartNumber)}!`);

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

0 Comments

    Add a comment
    10|10000 characters needed characters exceeded