Skip to content

fix(maths): detect long overflow in Pow.pow - #2

Draft
sambrossard wants to merge 1 commit into
masterfrom
fix/pow-overflow-detection
Draft

sambrossard wants to merge 1 commit into
masterfrom
fix/pow-overflow-detection

Conversation

@sambrossard

Copy link
Copy Markdown
Owner

Fixes #1 (mirror of upstream TheAlgorithms#7751).

Problem

Pow.pow(int a, int b) accumulated into a long with result *= a, so results larger than Long.MAX_VALUE silently wrapped: pow(2, 63) returned Long.MIN_VALUE and pow(2, 64) returned 0.

Change

  • Replace result *= a with Math.multiplyExact(result, a), which throws ArithmeticException on overflow.
  • Javadoc: document the new @throws ArithmeticException; drop the incorrect "base must be non-negative" note (negative bases are valid and tested).

Tests

  • testPowAtAndNearLongBounds: largest representable values still work, e.g. 2^62, (-2)^63 == Long.MIN_VALUE, 10^18, plus negative bases.
  • testPowThrowsOnOverflow: 2^63, 2^64, (-2)^64, 10^19, Integer.MAX_VALUE^3 throw ArithmeticException.
  • The new overflow tests fail on the old code (5/5) and pass with the fix.

Local CI

  • mvn verify: 10221 tests, 0 failures

  • checkstyle:check, spotbugs:check, check_structure.py: pass

  • clang-format 16 (the CI version) applied

  • pmd:check reports one violation that also exists on unmodified master (ExtendedKalmanFilter, unrelated to this change)

  • I have read CONTRIBUTING.md.

  • This pull request is all my own work -- I have not plagiarized it. (Written independently with AI assistance, credited in the commit; not derived from upstream PR Detect overflow in Pow.pow TheAlgorithms/Java#7752.)

  • All filenames are in PascalCase.

  • All functions and variable names follow Java naming conventions.

  • All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. (N/A: bug fix, no new algorithm)

  • All new algorithms include a corresponding test class that validates their functionality. (N/A: existing PowTest extended)

  • All new code is formatted with clang-format -i --style=file path/to/your/file.java

🤖 Generated with Claude Code

Pow.pow multiplied into a long without overflow checks, so results above
Long.MAX_VALUE silently wrapped (e.g. pow(2, 63) returned Long.MIN_VALUE).
Use Math.multiplyExact so overflow throws ArithmeticException, and update
the Javadoc (negative bases are valid; document the new exception).

Fixes #1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

[BUG] Pow.pow silently wraps when the result exceeds long range

1 participant