Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: trekhleb/javascript-algorithms
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: master
Choose a base ref
...
head repository: vamshi9/javascript-algorithms
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: patch-2
Choose a head ref
Able to merge. These branches can be automatically merged.
  • 1 commit
  • 1 file changed
  • 1 contributor

Commits on Sep 19, 2018

  1. Create Q_matrix.js

    This algorithm works in O(logn) time and much more powerful than the above algorithms
    vamshi9 authored Sep 19, 2018

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    b420e92 View commit details
Showing with 43 additions and 0 deletions.
  1. +43 −0 src/algorithms/math/fibonacci/Q_matrix.js
43 changes: 43 additions & 0 deletions src/algorithms/math/fibonacci/Q_matrix.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Calculate fibonacci number at specific position using Q matrix in O(logn) time.
*
* @param n
* @return {number}
*/
export default function fibonacciNth(n) {

//Require math.js library. If you're from python background, it is equivalent to numpy
const math = require('mathjs');

//mod is just for our convenience to see how quick large values are getting computed
const M = math.matrix([[1,1],[1,0]]),
Q = M,
mod = 10 ** 9 + 7;

//Using Q^n = Q^n/2 * Q^n/2
const power = (Q,n) => {
if(n == 1){
return M;
}

Q = power(Q,Math.floor(n/2));
Q = math.mod(math.multiply(Q,Q),mod);
if(n % 2 != 0){
Q = math.mod(math.multiply(Q,M),mod);
}

return Q;

}

const fibonacci = (Q,n) => {
//Q^n = [[Fn+1, Fn], [Fn, Fn-1]]
Q = power(Q,n-1);

//Q:{ _data:[[],[]], _size:[m, n], _datatype: string | number}
return Q['_data'][0][0];
}

return fibonacci(Q,n)

}