数学家Ulam建议从任何正整数n(n> 0)生成数字序列,如下所示-
If n is 1, it will stop. if n is even, the next number is n/2. if n is odd, the next number is 3 * n + 1. continue with the process until reaching 1.
这是前几个整数的一些示例-
2->1 3->10->5->16->8->4->2->1 4->2->1 6->3->10->5->16->8->4->2->1 7->22->11->34->17->52->26->13->40->20->10->5->16->8->4->2->1
我们需要编写一个接受数字并返回以该数字开头的Ulam序列的JavaScript函数。
为此的代码将是-
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 ]