--- id: 5a23c84252665b21eecc8028 title: Stern-Brocot sequence challengeType: 5 --- ## 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:
  2. Start by considering the second member of the sequence
  3. Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
  4. Append the considered member of the sequence to the end of the sequence:
  5. Consider the next member of the series, (the third member i.e. 2)
  6. GOTO 3
  7. Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
  8. Append the considered member of the sequence to the end of the sequence:
  9. Consider the next member of the series, (the fourth member i.e. 1)
Create a function that returns the $ n^{th} $ member of the sequence using the method outlined above.
## Instructions
## Tests
``` yml tests: - text: sternBrocot should be a function. testString: assert(typeof sternBrocot == 'function', 'sternBrocot should be a function.'); - text: sternBrocot(2) should return a number. testString: assert(typeof sternBrocot(2) == 'number', 'sternBrocot(2) should return a number.'); - text: sternBrocot(2) should return 3. testString: assert.equal(sternBrocot(2), 3, 'sternBrocot(2) should return 3.'); - text: sternBrocot(3) should return 5. testString: assert.equal(sternBrocot(3), 5, 'sternBrocot(3) should return 5.'); - text: sternBrocot(5) should return 11. testString: assert.equal(sternBrocot(5), 11, 'sternBrocot(5) should return 11.'); - text: sternBrocot(7) should return 19. testString: assert.equal(sternBrocot(7), 19, 'sternBrocot(7) should return 19.'); - text: sternBrocot(10) should return 39. testString: assert.equal(sternBrocot(10), 39, 'sternBrocot(10) should return 39.'); ```
## Challenge Seed
```js function sternBrocot (num) { // Good luck! } ```
## Solution
```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; } ```