Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> Co-authored-by: Kristofer Koishigawa <scissorsneedfoodtoo@gmail.com> Co-authored-by: Beau Carnes <beaucarnes@gmail.com>
		
			
				
	
	
	
		
			2.9 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	
			2.9 KiB
		
	
	
	
	
	
	
	
id, title, challengeType, isHidden, forumTopicId
| id | title | challengeType | isHidden | forumTopicId | 
|---|---|---|---|---|
| 5a23c84252665b21eecc8028 | Stern-Brocot sequence | 5 | false | 302324 | 
Description
- The first and second members of the sequence are both 1:
 - 1, 1
 - Start by considering the second member of the sequence
 - Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
 - 1, 1, 2
 - Append the considered member of the sequence to the end of the sequence:
 - 1, 1, 2, 1
 - Consider the next member of the series, (the third member i.e. 2)
 - GOTO 3
 - ─── Expanding another loop we get: ───
 - Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
 - 1, 1, 2, 1, 3
 - Append the considered member of the sequence to the end of the sequence:
 - 1, 1, 2, 1, 3, 2
 - Consider the next member of the series, (the fourth member i.e. 1)
 
Instructions
Tests
tests:
  - text: <code>sternBrocot</code> should be a function.
    testString: assert(typeof sternBrocot == 'function');
  - text: <code>sternBrocot(2)</code> should return a number.
    testString: assert(typeof sternBrocot(2) == 'number');
  - text: <code>sternBrocot(2)</code> should return <code>3</code>.
    testString: assert.equal(sternBrocot(2), 3);
  - text: <code>sternBrocot(3)</code> should return <code>5</code>.
    testString: assert.equal(sternBrocot(3), 5);
  - text: <code>sternBrocot(5)</code> should return <code>11</code>.
    testString: assert.equal(sternBrocot(5), 11);
  - text: <code>sternBrocot(7)</code> should return <code>19</code>.
    testString: assert.equal(sternBrocot(7), 19);
  - text: <code>sternBrocot(10)</code> should return <code>39</code>.
    testString: assert.equal(sternBrocot(10), 39);
Challenge Seed
function sternBrocot(num) {
  // Good luck!
}
Solution
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;
}