mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-04-13 22:00:19 -04:00
2.7 KiB
2.7 KiB
id, title, challengeType, forumTopicId, dashedName
| id | title | challengeType | forumTopicId | dashedName |
|---|---|---|---|---|
| 5a23c84252665b21eecc8028 | Sequenza di Stern-Brocot | 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.
- The first and second members of the sequence are both 1:
- 1, 1
- Inizia considerando il secondo elemento della serie
- Somma l'elemento considerato della sequenza e il precedente, (1 + 1) = 2, e aggiungilo alla fine della sequenza:
- 1, 1, 2
- Aggiungi l'elemento considerato alla fine della sequenza:
- 1, 1, 2, 1
- Considera l'elemento successivo della serie, (il terzo elemento, cioè 2)
- Vai a 3
- ─── Espandendo un altro ciclo otteniamo: ───
- Somma l'elemento considerato della sequenza e il suo predecessore, (2 + 1) = 3, e appendilo alla fine della sequenza:
- 1, 1, 2, 1, 3
- Aggiungi l'elemento considerato alla fine della sequenza:
- 1, 1, 2, 1, 3, 2
- Considera l'elemento successivo della serie, (il quarto elemento, cioè 1)
--instructions--
Crea una funzione che restituisce la posizione della serie di Stern-Brocot a cui n si trova per la prima volte, dove la serie è generata con il metodo mostrato sopra. Nota che questa sequenza usa indicizzazione che parte da 1.
--hints--
sternBrocot dovrebbe essere una funzione.
assert(typeof sternBrocot == 'function');
sternBrocot(2) dovrebbe restituire un numero.
assert(typeof sternBrocot(2) == 'number');
sternBrocot(2) dovrebbe restiture 3.
assert.equal(sternBrocot(2), 3);
sternBrocot(3) dovrebbe restituire 5.
assert.equal(sternBrocot(3), 5);
sternBrocot(5) dovrebbe restiture 11.
assert.equal(sternBrocot(5), 11);
sternBrocot(7) dovrebbe restiture 19.
assert.equal(sternBrocot(7), 19);
sternBrocot(10) dovrebbe restiture 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;
}