กฎ Ulam (Collatz): n=1 หยุด, n คู่ → n/2, n คี่ → 3n+1 ทำซ้ำจนถึง 1
ตัวอย่างโค้ด
const num = 7;
const generateUlam = num => {
const res = [num];
if (num && num === Math.abs(num) && isFinite(num)) {
while (num !== 1) {
if (num % 2) {
num = 3 * num + 1;
} else {
num /= 2;
}
res.push(num);
}
} else {
return false;
}
return res;
};
console.log(generateUlam(num));
console.log(generateUlam(3));ผลลัพธ์
[ 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 ] [ 3, 10, 5, 16, 8, 4, 2, 1 ]
คำอธิบาย: นามหลายชื่อ: Ulam sequence, Collatz conjecture, 3n+1 problem ตรวจสอบ input เป็น positive integer แล้ววนลูปตามกฎจนถึง 1 เก็บทุกขั้นตอนในอาร์เรย์