Back to Freecodecamp

Stern-Brocot sequence

curriculum/challenges/english/blocks/rosetta-code-challenges/5a23c84252665b21eecc8028.md

latest2.5 KB
Original Source

--description--

For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the <a href="https://rosettacode.org/wiki/Fibonacci_sequence" target="_blank" rel="noopener noreferrer nofollow">Fibonacci sequence</a>.

<ol> <li>The first and second members of the sequence are both 1:</li> <ul><li>1, 1</li></ul> <li>Start by considering the second member of the sequence</li> <li>Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:</li> <ul><li>1, 1, 2</li></ul> <li>Append the considered member of the sequence to the end of the sequence:</li> <ul><li>1, 1, 2, 1</li></ul> <li>Consider the next member of the series, (the third member i.e. 2)</li> <li>GOTO 3 </li> <ul> <li></li> <li> ─── Expanding another loop we get: ───</li> <li></li> </ul> <li>Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:</li> <ul><li>1, 1, 2, 1, 3</li></ul> <li>Append the considered member of the sequence to the end of the sequence:</li> <ul><li>1, 1, 2, 1, 3, 2</li></ul> <li>Consider the next member of the series, (the fourth member i.e. 1)</li> </ol>

--instructions--

Create a function that returns the position in the Stern-Brocot sequence at which $ n $ is first encountered, where the sequence is generated with the method outlined above. Note that this sequence uses 1 based indexing.

--hints--

sternBrocot should be a function.

js
assert(typeof sternBrocot == 'function');

sternBrocot(2) should return a number.

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

sternBrocot(2) should return 3.

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

sternBrocot(3) should return 5.

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

sternBrocot(5) should return 11.

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

sternBrocot(7) should return 19.

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

sternBrocot(10) should return 39.

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

--seed--

--seed-contents--

js
function sternBrocot(num) {

}

--solutions--

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