如何在 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