forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacci.js
More file actions
Latest commit
195 lines (168 loc) · 5.09 KB
/
Copy pathFibonacci.js
File metadata and controls
195 lines (168 loc) · 5.09 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Extension_to_negative_integers
constFibonacciIterative=(num)=>{
constisNeg=num<0
if(isNeg)num*=-1
constsequence=[0]
if(num>=1)sequence.push(1)
if(num>=2)sequence.push(isNeg ? -1 : 1)
for(leti=2;i<num;i++){
sequence.push(
isNeg ? sequence[i-1]-sequence[i] : sequence[i]+sequence[i-1]
)
}
returnsequence
}
constFibonacciGenerator=function*(neg){
leta=0
letb=1
yielda
while(true){
yieldb;
[a,b]=neg ? [b,a-b] : [b,a+b]
}
}
constlist=[]
constFibonacciRecursive=(num)=>{
constisNeg=num<0
if(isNeg)num*=-1
return(()=>{
switch(list.length){
case0:
list.push(0)
returnFibonacciRecursive(num)
case1:
list.push(1)
returnFibonacciRecursive(num)
casenum+1:
returnlist
default:
list.push(list.at(-1)+list.at(-2))
returnFibonacciRecursive(num)
}
})().map((fib,i)=>fib*(isNeg ? (-1)**(i+1) : 1))
}
constdict=newMap()
constFibonacciRecursiveDP=(stairs)=>{
constisNeg=stairs<0
if(isNeg)stairs*=-1
if(stairs<=1)returnstairs
// Memoize stair count
if(dict.has(stairs))return(isNeg ? (-1)**(stairs+1) : 1)*dict.get(stairs)
constres=FibonacciRecursiveDP(stairs-1)+FibonacciRecursiveDP(stairs-2)
dict.set(stairs,res)
return(isNeg ? (-1)**(stairs+1) : 1)*res
}
// Algorithms
// Calculates Fibonacci(n) such that Fibonacci(n) = Fibonacci(n - 1) + Fibonacci(n - 2)
// Fibonacci(0) = Fibonacci(1) = 1
// Uses a bottom up dynamic programming approach
// Solve each sub-problem once, using results of previous sub-problems
// which are n-1 and n-2 for Fibonacci numbers
// Although this algorithm is linear in space and time as a function
// of the input value n, it is exponential in the size of n as
// a function of the number of input bits
// @Satzyakiz
constFibonacciDpWithoutRecursion=(num)=>{
constisNeg=num<0
if(isNeg)num*=-1
consttable=[0]
table.push(1)
table.push(isNeg ? -1 : 1)
for(leti=2;i<num;++i){
table.push(
isNeg ? table[i-1]-table[i] : table[i]+table[i-1]
)
}
returntable
}
// Using Matrix exponentiation to find n-th fibonacci in O(log n) time
constcopyMatrix=(A)=>{
returnA.map(row=>row.map(cell=>cell))
}
constIdentity=(size)=>{
constisBigInt=typeofsize==='bigint'
constZERO=isBigInt ? 0n : 0
constONE=isBigInt ? 1n : 1
size=Number(size)
constI=Array(size).fill(null).map(()=>Array(size).fill())
returnI.map((row,rowIdx)=>row.map((_col,colIdx)=>{
returnrowIdx===colIdx ? ONE : ZERO
}))
}
// A of size (l x m) and B of size (m x n)
// product C will be of size (l x n).
// both matrices must have same-type numeric values
// either both BigInt or both Number
constmatrixMultiply=(A,B)=>{
A=copyMatrix(A)
B=copyMatrix(B)
constisBigInt=typeofA[0][0]==='bigint'
constl=A.length
constm=B.length
constn=B[0].length// Assuming non-empty matrices
constC=Array(l).fill(null).map(()=>Array(n).fill())
for(leti=0;i<l;i++){
for(letj=0;j<n;j++){
C[i][j]=isBigInt ? 0n : 0
for(letk=0;k<m;k++){
C[i][j]+=A[i][k]*B[k][j]
}
}
}
returnC
}
/**
* Computes A raised to the power n i.e. pow(A, n) where A is a square matrix
* @param {*} A the square matrix
* @param {*} n the exponent
*/
// A is a square matrix
constmatrixExpo=(A,n)=>{
A=copyMatrix(A)
constisBigInt=typeofn==='bigint'
constZERO=isBigInt ? 0n : 0
constTWO=isBigInt ? 2n : 2
// Just like Binary exponentiation mentioned in ./BinaryExponentiationIterative.js
letresult=Identity((isBigInt ? BigInt : Number)(A.length))// Identity matrix
while(n>ZERO){
if(n%TWO!==ZERO)result=matrixMultiply(result,A)
n/=TWO
if(!isBigInt)n=Math.floor(n)
if(n>ZERO)A=matrixMultiply(A,A)
}
returnresult
}
constFibonacciMatrixExpo=(num)=>{
constisBigInt=typeofnum==='bigint'
constZERO=isBigInt ? 0n : 0
constONE=isBigInt ? 1n : 1
// F(0) = 0, F(1) = 1
// F(n) = F(n-1) + F(n-2)
// Consider below matrix multiplication:
// | F(n) | |1 1| |F(n-1)|
// | | = | | * | |
// |F(n-1)| |1 0| |F(n-2)|
// Let's rewrite it as F(n, n-1) = A * F(n-1, n-2)
// or F(n, n-1) = A * A * F(n-2, n-3)
// or F(n, n-1) = pow(A, n-1) * F(1, 0)
if(num===ZERO)returnnum
constisNeg=num<0
if(isNeg)num*=-ONE
constA=[
[ONE,ONE],
[ONE,ZERO]
]
constpoweredA=matrixExpo(A,num-ONE)// A raised to the power n-1
letF=[
[ONE],
[ZERO]
]
F=matrixMultiply(poweredA,F)
returnF[0][0]*(isNeg ? (-ONE)**(num+ONE) : ONE)
}
export{FibonacciDpWithoutRecursion}
export{FibonacciIterative}
export{FibonacciGenerator}
export{FibonacciRecursive}
export{FibonacciRecursiveDP}
export{FibonacciMatrixExpo}