@@ -102,14 +102,17 @@ const matrixMultiply = (A, B) => {
102102 return C
103103}
104104
105+ /**
106+ * Computes A raised to the power n i.e. pow(A, n) where A is a square matrix
107+ * @param {* } A the square matrix
108+ * @param {* } n the exponent
109+ */
105110// A is a square matrix
106111const matrixExpo = ( A , n ) => {
107112 A = copyMatrix ( A )
108- if ( n === 0 ) return Identity ( A . length ) // Identity matrix
109- if ( n === 1 ) return A
110113
111114 // Just like Binary exponentiation mentioned in ./BinaryExponentiationIterative.js
112- let result = Identity ( A . length )
115+ let result = Identity ( A . length ) // Identity matrix
113116 while ( n > 0 ) {
114117 if ( n % 2 !== 0 ) result = matrixMultiply ( result , A )
115118 n = Math . floor ( n / 2 )
@@ -127,15 +130,17 @@ const FibonacciMatrixExpo = (n) => {
127130 // | | = | | * | |
128131 // |F(n-1)| |1 0| |F(n-2)|
129132
130- // F(n, n-1) = pow(A, n-1) * F(1, 0)
133+ // Let's rewrite it as F(n, n-1) = A * F(n-1, n-2)
134+ // or F(n, n-1) = A * A * F(n-2, n-3)
135+ // or F(n, n-1) = pow(A, n-1) * F(1, 0)
131136
132137 if ( n === 0 ) return 0
133138
134139 const A = [
135140 [ 1 , 1 ] ,
136141 [ 1 , 0 ]
137142 ]
138- const poweredA = matrixExpo ( A , n - 1 ) // A raise to the power n
143+ const poweredA = matrixExpo ( A , n - 1 ) // A raised to the power n-1
139144 let F = [
140145 [ 1 ] ,
141146 [ 0 ]
0 commit comments