diff --git a/Maths/MatrixExponentiationRecursive.js b/Maths/MatrixExponentiationRecursive.js index e86ceebe29..fece201aee 100644 --- a/Maths/MatrixExponentiationRecursive.js +++ b/Maths/MatrixExponentiationRecursive.js @@ -59,7 +59,7 @@ export const MatrixExponentiationRecursive = (mat, m) => { return MatMult(tmp, mat) } else { // tmp = mat ^ m/2 - const tmp = MatrixExponentiationRecursive(mat, m >> 1) + const tmp = MatrixExponentiationRecursive(mat, Math.floor(m / 2)) // return tmp * tmp = (mat ^ m/2) ^ 2 = mat ^ m return MatMult(tmp, tmp) } diff --git a/Maths/test/MatrixExponentiationRecursive.test.js b/Maths/test/MatrixExponentiationRecursive.test.js new file mode 100644 index 0000000000..b1c0566ec2 --- /dev/null +++ b/Maths/test/MatrixExponentiationRecursive.test.js @@ -0,0 +1,21 @@ +import { MatrixExponentiationRecursive } from '../MatrixExponentiationRecursive' + +describe('MatrixExponentiationRecursive', () => { + it.each([0, 1, 2, 2 ** 31, 2 ** 32, Number.MAX_SAFE_INTEGER])( + 'should preserve the exponent %i without signed 32-bit truncation', + (exponent) => { + const matrix = [ + [1, 1], + [0, 1] + ] + expect(MatrixExponentiationRecursive(matrix, exponent)).toEqual([ + [1, exponent], + [0, 1] + ]) + expect(matrix).toEqual([ + [1, 1], + [0, 1] + ]) + } + ) +})