Files
freeCodeCamp/curriculum/challenges/chinese/22-rosetta-code/rosetta-code-challenges/stern-brocot-sequence.md
2024-01-24 19:52:36 +01:00

2.5 KiB
Raw Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
5a23c84252665b21eecc8028 Stern-Brocot 序列 1 302324 stern-brocot-sequence

--description--

For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.

  1. The first and second members of the sequence are both 1:
    • 1, 1
  2. 首先考虑序列的第二个成员
  3. 将序列的考虑成员与其先例相加,(1 + 1) = 2并将其附加到序列的末尾
    • 1, 1, 2
  4. 将序列的考虑成员附加到序列的末尾:
    • 1, 1, 2, 1
  5. 考虑该系列的下一个成员(第三个成员,即 2
  6. GOTO 3
    • ──── 展开另一个循环,我们得到:────
  7. 将序列的考虑成员与其先例相加,(2 + 1) = 3并将其附加到序列的末尾
    • 1, 1, 2, 1, 3
  8. 将序列的考虑成员附加到序列的末尾:
    • 1, 1, 2, 1, 3, 2
  9. 考虑该系列的下一个成员(第四个成员,即 1

--instructions--

创建一个函数,该函数返回 Stern-Brocot 序列中第一次遇到 n 的位置,该序列是使用上述方法生成的。 请注意,此序列使用基于 1 的索引。

--hints--

sternBrocot 应该是一个函数。

assert(typeof sternBrocot == 'function');

sternBrocot(2) 应该返回一个数字。

assert(typeof sternBrocot(2) == 'number');

sternBrocot(2) 应该返回 3

assert.equal(sternBrocot(2), 3);

sternBrocot(3) 应该返回 5

assert.equal(sternBrocot(3), 5);

sternBrocot(5) 应该返回 11

assert.equal(sternBrocot(5), 11);

sternBrocot(7) 应该返回 19

assert.equal(sternBrocot(7), 19);

sternBrocot(10) 应该返回 39

assert.equal(sternBrocot(10), 39);

--seed--

--seed-contents--

function sternBrocot(num) {

}

--solutions--

function sternBrocot(num) {
  function f(n) {
    return n < 2
      ? n
      : n & 1
      ? f(Math.floor(n / 2)) + f(Math.floor(n / 2 + 1))
      : f(Math.floor(n / 2));
  }

  function gcd(a, b) {
    return a ? (a < b ? gcd(b % a, a) : gcd(a % b, b)) : b;
  }
  var n;
  for (n = 1; f(n) != num; n++);
  return n;
}