mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-13 06:04:13 -04:00
113 lines
2.5 KiB
Markdown
113 lines
2.5 KiB
Markdown
---
|
||
id: 5a23c84252665b21eecc8028
|
||
title: Stern-Brocot 序列
|
||
challengeType: 1
|
||
forumTopicId: 302324
|
||
dashedName: 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 <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>首先考虑序列的第二个成员</li>
|
||
<li>将序列的考虑成员与其先例相加,(1 + 1) = 2,并将其附加到序列的末尾:</li>
|
||
<ul><li>1, 1, 2</li></ul>
|
||
<li>将序列的考虑成员附加到序列的末尾:</li>
|
||
<ul><li>1, 1, 2, 1</li></ul>
|
||
<li>考虑该系列的下一个成员(第三个成员,即 2)</li>
|
||
<li>GOTO 3 </li>
|
||
<ul>
|
||
<li></li>
|
||
<li> ──── 展开另一个循环,我们得到:────</li>
|
||
<li></li>
|
||
</ul>
|
||
<li>将序列的考虑成员与其先例相加,(2 + 1) = 3,并将其附加到序列的末尾:</li>
|
||
<ul><li>1, 1, 2, 1, 3</li></ul>
|
||
<li>将序列的考虑成员附加到序列的末尾:</li>
|
||
<ul><li>1, 1, 2, 1, 3, 2</li></ul>
|
||
<li>考虑该系列的下一个成员(第四个成员,即 1)</li>
|
||
</ol>
|
||
|
||
# --instructions--
|
||
|
||
创建一个函数,该函数返回 Stern-Brocot 序列中第一次遇到 $ n $ 的位置,该序列是使用上述方法生成的。 请注意,此序列使用基于 1 的索引。
|
||
|
||
# --hints--
|
||
|
||
`sternBrocot` 应该是一个函数。
|
||
|
||
```js
|
||
assert(typeof sternBrocot == 'function');
|
||
```
|
||
|
||
`sternBrocot(2)` 应该返回一个数字。
|
||
|
||
```js
|
||
assert(typeof sternBrocot(2) == 'number');
|
||
```
|
||
|
||
`sternBrocot(2)` 应该返回 `3`。
|
||
|
||
```js
|
||
assert.equal(sternBrocot(2), 3);
|
||
```
|
||
|
||
`sternBrocot(3)` 应该返回 `5`。
|
||
|
||
```js
|
||
assert.equal(sternBrocot(3), 5);
|
||
```
|
||
|
||
`sternBrocot(5)` 应该返回 `11`。
|
||
|
||
```js
|
||
assert.equal(sternBrocot(5), 11);
|
||
```
|
||
|
||
`sternBrocot(7)` 应该返回 `19`。
|
||
|
||
```js
|
||
assert.equal(sternBrocot(7), 19);
|
||
```
|
||
|
||
`sternBrocot(10)` 应该返回 `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;
|
||
}
|
||
```
|