Skip to content

fix: preserve large exponents in recursive matrix powers - #2033

Open
lanqing431 wants to merge 1 commit into
TheAlgorithms:masterfrom
lanqing431:fix/matrix-power-large-exponents
Open

lanqing431 wants to merge 1 commit into
TheAlgorithms:masterfrom
lanqing431:fix/matrix-power-large-exponents

Conversation

@lanqing431

Copy link
Copy Markdown

Describe your change:

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Documentation change?

MatrixExponentiationRecursive([[1, 1], [0, 1]], 2 ** 31) overflows the call stack. The >> 1 step converts the exponent to a signed 32-bit integer; the recursion eventually gets stuck at -1. At 2 ** 32 it silently returns the identity matrix instead of the correct power.

Use Math.floor(m / 2) to halve the exponent without truncating its bits. The six new cases use a triangular matrix whose exact power is [[1, n], [0, 1]], covering zero, small exponents, 2 ** 31, 2 ** 32 and Number.MAX_SAFE_INTEGER. They also check that the input matrix is unchanged.

Validation (Node.js 24.22.0): the three large-exponent cases fail on unchanged master. npm test -- --maxWorkers=2 --minWorkers=1 passes all 11976 tests in 347 files. npm run check-style and git diff --check pass.

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is my own contribution and does not copy another proposed fix.
  • This PR only changes one algorithm file and its tests.
  • All new files use the existing Maths/test directory and naming convention.

Prepared with OpenAI Codex assistance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant