Skip to content

Commit 94e334f

Browse files
authored
Create nth-fibonacci.js
1 parent 15e5d7d commit 94e334f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

nth-fibonacci.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const fiboRecursive = n => {
2+
if (n < 2) {
3+
return n;
4+
} else {
5+
return fiboRecursive(n - 1) + fiboRecursive(n - 2);
6+
}
7+
};
8+
9+
const fibo = n => {
10+
const array = [];
11+
let i = 2;
12+
array.push(0);
13+
array.push(1);
14+
while (i < n) {
15+
array.push(array[i - 1] + array[i - 2]);
16+
i++;
17+
}
18+
return array[i - 1];
19+
};
20+
21+
const spaceOptimizedFibo = n => {
22+
let a = 0,
23+
b = 1,
24+
c,
25+
i = 3;
26+
27+
while (i <= n) {
28+
c = a + b;
29+
a = b;
30+
b = c;
31+
++i;
32+
}
33+
34+
return c;
35+
};

0 commit comments

Comments
 (0)