-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfibonacci.js
53 lines (41 loc) · 936 Bytes
/
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
// ================================================
// Fibonacci Sequence
// ================================================
function fibonacciGenerator(n) {
var output = [];
if (n === 1) {
output = [0];
} else if (n === 2) {
output = [0, 1];
} else {
output = [0, 1];
for (var i = 2; i < n; i++) {
output.push(output[output.length - 2] + output[output.length - 1]);
}
}
return output;
}
function fibonacci(num) {
var a = 1,
b = 0,
temp;
while (num >= 0) {
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
// Recursive Fibonacci
function fibonacci(num) {
if (num <= 1) return 1;
return fibonacci(num - 1) + fibonacci(num - 2);
}
// Memoization Fibonacci
function fibonacci(num, memo) {
memo = memo || {};
if (memo[num]) return memo[num];
if (num <= 1) return 1;
return (memo[num] = fibonacci(num - 1, memo) + fibonacci(num - 2, memo));
}