JavaScript_14.콜라츠 추측

hams·2023년 3월 28일
0

algorithm

목록 보기
14/62

Q.
1937년 Collatz란 사람에 의해 제기된 이 추측은, 주어진 수가 1이 될 때까지 다음 작업을 반복하면, 모든 수를 1로 만들 수 있다는 추측입니다. 작업은 다음과 같습니다.


function solution(num) {
  let count = 0
  if(num == 1) return 0
   function repeat(num) {
    if(count == 500) return -1
    if(num == 1) return count
        count += 1
    if(num % 2) return repeat(num * 3 + 1)
    return repeat(num / 2) 
  }
    return repeat(num)
}

난,,, 재귀함수 밖에 생각이 안났다

다른 사람의 코드1

function collatz(num) {
    var answer = 0;
    while(num !=1 && answer !=500){
        num%2==0 ? num = num/2 : num = num*3 +1;
    answer++;
  }
    return num == 1 ? answer : -1;
}

다른 사람의 코드 2

function collatz(num, count = 0) {
    return (num == 1) ? ((count >= 500) ? -1 : count) : collatz((num % 2 == 0) ? num / 2 : (num * 3) + 1, ++count);
}

다른 사람의 코드3

const solution = (num) => collatzGuessCount(num, 0);

const collatzGuessCount = (num, acc) => 
  (num === 1) ? ((acc > 500) ? -1 : acc) : collatzGuessCount(processCollatz(num), acc + 1);

const processCollatz = (num) => (num % 2 === 0) ? (num / 2) : (num * 3 + 1);

0개의 댓글