Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions Maths/Fibonacci.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,17 @@ const matrixMultiply = (A, B) => {
return C
}

/**
* 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
const matrixExpo = (A, n) => {
A = copyMatrix(A)
if (n === 0) return Identity(A.length) // Identity matrix
if (n === 1) return A

// Just like Binary exponentiation mentioned in ./BinaryExponentiationIterative.js
let result = Identity(A.length)
let result = Identity(A.length) // Identity matrix
while (n > 0) {
if (n % 2 !== 0) result = matrixMultiply(result, A)
n = Math.floor(n / 2)
Expand All @@ -127,15 +130,17 @@ const FibonacciMatrixExpo = (n) => {
// | | = | | * | |
// |F(n-1)| |1 0| |F(n-2)|

// F(n, n-1) = pow(A, n-1) * F(1, 0)
// 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 (n === 0) return 0

const A = [
[1, 1],
[1, 0]
]
const poweredA = matrixExpo(A, n - 1) // A raise to the power n
const poweredA = matrixExpo(A, n - 1) // A raised to the power n-1
let F = [
[1],
[0]
Expand Down
5 changes: 5 additions & 0 deletions Maths/test/Fibonacci.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ describe('Fibonanci', () => {
})

it('should return number for FibonnaciMatrixExpo', () => {
expect(FibonacciMatrixExpo(0)).toBe(0)
expect(FibonacciMatrixExpo(1)).toBe(1)
expect(FibonacciMatrixExpo(2)).toBe(1)
expect(FibonacciMatrixExpo(3)).toBe(2)
expect(FibonacciMatrixExpo(4)).toBe(3)
expect(FibonacciMatrixExpo(5)).toBe(5)
})
})