-
Notifications
You must be signed in to change notification settings - Fork 0
/
fibonacci.js
60 lines (52 loc) · 2.42 KB
/
fibonacci.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/* _ _ _ _ _ _ _ _
(_)(_)(_)(_)(_)(_) (_) (_)
(_) _ _ (_) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
(_) _ _ (_)(_) (_)(_)(_)(_)_ _ (_)(_)(_) _ (_)(_)(_)(_)_ (_)(_)(_) _ _(_)(_)(_)_(_)(_)(_)(_)(_)
(_)(_)(_) (_) (_) (_)(_) (_)(_) (_) _ _ _ (_) (_) (_) (_)
(_) (_) (_) (_)(_) (_)(_) (_) _(_)(_)(_)(_) (_) (_) (_)
(_) _ (_) _ (_) _ _ _(_)(_) _ _ _ (_)(_) (_)(_)_ _ _ (_)_(_)_ _ _(_)_ _ _ _ (_) _
(_) (_)(_)(_)(_)(_)(_)(_) (_)(_)(_) (_) (_) (_)(_)(_) (_) (_)(_)(_) (_)(_)(_)(_)(_)(_)
*/
/**
* Genera la secuencia de fibonacci
* dado el limite, utilizando while loop
* @param {number} limit limite de la secuencia
* @returns {Array<number>} secuencia de Fibonacci
*/
function fibonacciSequenceWithWhile(limit) {
const sequence = [0, 1];
while (sequence.length <= limit) {
sequence.push(
sequence[sequence.length - 1] + sequence[sequence.length - 2]
);
}
return sequence;
}
fibonacciSequenceWithWhile(5); // [0, 1, 1, 2, 3, 5]
/**
* Genera la secuencia de fibonacci
* dado el limite, utilizando for loop
* @param {number} limit limite de la secuencia
* @returns {Array<number>} secuencia de Fibonacci
*/
function fibonacciSequenceWithFor(limit) {
const sequence = [0, 1];
for (let i = 2; i <= limit; i++) {
sequence[i] = sequence[sequence.length - 1] + sequence[sequence.length - 2];
}
return sequence;
}
fibonacciSequenceWithFor(5); // [0, 1, 1, 2, 3, 5]
console.log(fibonacciSequenceWithWhile(5));
console.log(fibonacciSequenceWithFor(15).length);
/**
* Obtener el numero de la serie de fibonacci
* segun el numero proporcionado
* @param {*} n valor para identificar el numero de la serie
* @returns {number} numero de fibonacci segun el indice
*/
const fibonacciWithRecursivity = (n) => {
if (n < 2) return n;
return fibonacciWithRecursivity(n - 2) + fibonacciWithRecursivity(n - 1);
};
console.log(fibonacciWithRecursivity(5)); // 5