Skip to content

Commit cea63e7

Browse files
committed
fix: preserve large exponents in recursive matrix powers
1 parent 5c39e87 commit cea63e7

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

‎Maths/MatrixExponentiationRecursive.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ export const MatrixExponentiationRecursive = (mat, m) => {
5959
return MatMult(tmp, mat)
6060
} else {
6161
// tmp = mat ^ m/2
62-
const tmp = MatrixExponentiationRecursive(mat, m >> 1)
62+
const tmp = MatrixExponentiationRecursive(mat, Math.floor(m / 2))
6363
// return tmp * tmp = (mat ^ m/2) ^ 2 = mat ^ m
6464
return MatMult(tmp, tmp)
6565
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { MatrixExponentiationRecursive } from '../MatrixExponentiationRecursive'
2+
3+
describe('MatrixExponentiationRecursive', () => {
4+
it.each([0, 1, 2, 2 ** 31, 2 ** 32, Number.MAX_SAFE_INTEGER])(
5+
'should preserve the exponent %i without signed 32-bit truncation',
6+
(exponent) => {
7+
const matrix = [
8+
[1, 1],
9+
[0, 1]
10+
]
11+
expect(MatrixExponentiationRecursive(matrix, exponent)).toEqual([
12+
[1, exponent],
13+
[0, 1]
14+
])
15+
expect(matrix).toEqual([
16+
[1, 1],
17+
[0, 1]
18+
])
19+
}
20+
)
21+
})

0 commit comments

Comments
 (0)