1. 프로그래머스
Lv1. 콜라츠 추측
function solution(num) {
let newNum = 0;
let newNumArr = [];
if(num === 1){
return 0
}
if(num%2 === 0){
newNum = num/2
newNumArr.push(newNum)
}
else{
newNum = (num*3)+1
newNumArr.push(newNum)
}
let i = 0;
do{
if(newNumArr[i]%2 === 0){
newNum = newNumArr[i]/2
newNumArr.push(newNum)
i++
}
else{
newNum = (newNumArr[i]*3)+1
newNumArr.push(newNum)
i++
}
}while(newNumArr[newNumArr.length-1] !== 1)
if(i > 500){
return -1
}
else{
return i+1
}
}
while(newNumArr[newNumArr.length-1] !== 1)
반환값이 i+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;
}
function collatz(num, count = 0) {
return (num == 1) ? ((count >= 500) ? -1 : count) : collatz((num % 2 == 0) ? num / 2 : (num * 3) + 1, ++count);
}