使用 JavaScript 查找递增序列的第 n 个元素
问题
考虑定义如下的递增序列-
数seq(0)=1是seq中的第一个。
对于seq中的每个x,则y=2*x+1和z=3*x+1也必须在seq中。
seq中没有其他数字。
因此,这个序列的前几项将是-
[1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]
我们需要编写一个函数,它接受一个数字n并返回这个序列的第n项。
示例
以下是代码-
const num = 10;
const findNth = n => {
let seq = [1], x = 0, y = 0
for (let i = 0; i < n; i++) {
let nextX = 2 * seq[x] + 1, nextY = 3 * seq[y] + 1
if (nextX <= nextY) {
seq.push(nextX)
x++
if (nextX == nextY)
y++
} else {
seq.push(nextY)
y++
}
}
return seq[n];
}
console.log(findNth(num));输出结果22