如何在 JavaScript 中构建乌拉姆数列?
数学家乌拉姆提出根据任何正整数 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
我们需要编写一个 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 ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
JavaScript
PHP