Skip to content

Commit b420e92

Browse files
authoredSep 19, 2018
Create Q_matrix.js
This algorithm works in O(logn) time and much more powerful than the above algorithms
1 parent 2451db9 commit b420e92

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
 
+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Calculate fibonacci number at specific position using Q matrix in O(logn) time.
3+
*
4+
* @param n
5+
* @return {number}
6+
*/
7+
export default function fibonacciNth(n) {
8+
9+
//Require math.js library. If you're from python background, it is equivalent to numpy
10+
const math = require('mathjs');
11+
12+
//mod is just for our convenience to see how quick large values are getting computed
13+
const M = math.matrix([[1,1],[1,0]]),
14+
Q = M,
15+
mod = 10 ** 9 + 7;
16+
17+
//Using Q^n = Q^n/2 * Q^n/2
18+
const power = (Q,n) => {
19+
if(n == 1){
20+
return M;
21+
}
22+
23+
Q = power(Q,Math.floor(n/2));
24+
Q = math.mod(math.multiply(Q,Q),mod);
25+
if(n % 2 != 0){
26+
Q = math.mod(math.multiply(Q,M),mod);
27+
}
28+
29+
return Q;
30+
31+
}
32+
33+
const fibonacci = (Q,n) => {
34+
//Q^n = [[Fn+1, Fn], [Fn, Fn-1]]
35+
Q = power(Q,n-1);
36+
37+
//Q:{ _data:[[],[]], _size:[m, n], _datatype: string | number}
38+
return Q['_data'][0][0];
39+
}
40+
41+
return fibonacci(Q,n)
42+
43+
}

0 commit comments

Comments
 (0)
Please sign in to comment.