Max Collatz Sequence Length ( 5 kyu )

문제

In this kata we will take a look at the length of collatz sequences. And how they evolve. Write a function that take a positive integer n and return the number between 1 and n that has the maximum Collatz sequence length and the maximum length. The output has to take the form of an array [number, maxLength] For exemple the Collatz sequence of 4 is [4,2,1], 3 is [3,10,5,16,8,4,2,1], 2 is [2,1], 1 is [1], so MaxCollatzLength(4) should return [3,8]. If n is not a positive integer, the function have to return [].

n 이하의 숫자중 콜라츠 순서를 적용해 가장 긴 길이를 리턴하는 문제

풀이

function MaxCollatzLength(n) {
  if ( n <= 0 || typeof n !== 'number' ) return [];
  let max = [1,1], temp, count;
  for ( let i = 2; i <= n; i++ ) {
    temp = i;
    count = 0;
    while ( temp > 1 ) {
      if ( temp % 2 === 0 ) temp = temp/2;
      else temp = temp*3 + 1;
      count++;
    }
    if ( count > max[1] ) max = [i, count+1]
  }
  return max;
}

temp에 n으로 시작해서 몇개의 콜라츠 순열이 나오는지 담고 연산 횟수를 count로 해서 최댓값을 리턴하는 방법

다른 사람의 풀이

별로임


+ Recent posts