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

2.9 KiB

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
5a23c84252665b21eecc8028 スターン=ブロコット数列 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. 数列の2番目の要素に注目するところから開始します。
  3. 数列の注目した要素とその前の要素を合計すると (1 + 1) = 2 となり、これを数列の末尾に追加します。
    • 1, 1, 2
  4. 注目しておいた要素を数列の最後に追加します。
    • 1, 1, 2, 1
  5. 数列の次の要素に注目します。(3 番目の要素、すなわち 2)
  6. 3 に戻ります。
    • ── さらに、ループを繰り返します ───
  7. 数列の注目した要素とその前の要素を合計すると (2 + 1) = 3 となり、これを数列の末尾に追加します。
    • 1, 1, 2, 1, 3
  8. 注目しておいた要素を数列の最後に追加します。
    • 1, 1, 2, 1, 3, 2
  9. 数列の次の要素に注目します。(4 番目の要素、すなわち 1)

--instructions--

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;
}