Skip to content

Commit 6f0029c

Browse files
NourBcitsvinayak
andauthored
Create Fibonacci.js (#133)
* Create Fibonacci.js * Update Fibonacci.js Co-authored-by: vinayak <itssvinayak@gmail.com>
1 parent e57ec1f commit 6f0029c

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

maths/Fibonacci.js

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
const list = []
2+
3+
const FibonacciIterative = (nth) => {
4+
const sequence = []
5+
6+
if (nth >= 1) sequence.push(1)
7+
if (nth >= 2) sequence.push(1)
8+
9+
for (let i = 2; i < nth; i++) {
10+
sequence.push(sequence[i - 1] + sequence[i - 2])
11+
}
12+
13+
return sequence
14+
}
15+
16+
const FibonacciRecursive = (number) => {
17+
return (() => {
18+
switch (list.length) {
19+
case 0:
20+
list.push(1)
21+
return FibonacciRecursive(number)
22+
case 1:
23+
list.push(1)
24+
return FibonacciRecursive(number)
25+
case number:
26+
return list
27+
default:
28+
list.push(list[list.length - 1] + list[list.length - 2])
29+
return FibonacciRecursive(number)
30+
}
31+
})()
32+
}
33+
34+
const dict = new Map()
35+
36+
const FibonacciRecursiveDP = (stairs) => {
37+
if (stairs <= 0) return 0
38+
if (stairs === 1) return 1
39+
40+
// Memoize stair count
41+
if (dict.has(stairs)) return dict.get(stairs)
42+
43+
const res =
44+
FibonacciRecursiveDP(stairs - 1) + FibonacciRecursiveDP(stairs - 2)
45+
46+
dict.set(stairs, res)
47+
48+
return res
49+
}
50+
51+
// testing
52+
53+
console.log(FibonacciIterative(5))
54+
// Output: [ 1, 1, 2, 3, 5 ]
55+
console.log(FibonacciRecursive(5))
56+
// Output: [ 1, 1, 2, 3, 5 ]
57+
58+
console.log(FibonacciRecursiveDP(5))
59+
// Output: 5

0 commit comments

Comments
 (0)