Skip to content

Return ±1 for -1 raised to an integer too large for an int [patch] - #153

Merged
matt-edmondson merged 2 commits into
mainfrom
fix/pow-negative-one-128
Oct 6, 2026
Merged

matt-edmondson merged 2 commits into
mainfrom
fix/pow-negative-one-128

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #128

What changed

Pow raises an integer power by repeated squaring, counting the exponent down as an int. An exponent with magnitude of 2^31 or more doesn't fit, so (-1)^n threw OverflowException for those exponents, even though the result is always ±1.

A base of +1 already returns early through IsUnit. This adds the matching early return for −1 at the top of the integer branch: IsEvenInteger(power) ? One : NegativeOne.

A fractional power of −1 still throws ArgumentOutOfRangeException, as any negative base does. Any other base with an exponent that large still overflows the result's exponent, so that exception stays, as the issue asks.

Tests

  • New PowOfNegativeOneIsParityOfAnyIntegerPower covers the three failing calls from the issue (2147483648, -2147483648, 1e20), the odd values just past the int range (±2147483649), and in-range values (2147483647, 2, -3).
  • Checked that the test catches the bug: with the PreciseNumber.cs change stashed, the five out-of-range cases fail. With it, all 448 tests pass.
  • dotnet build -c Release of the library succeeds.

🤖 Generated with Claude Code

https://claude.ai/code/session_01JGKBe8wvU3P6jYj9MkNC69


Generated by Claude Code

claude added 2 commits October 6, 2026 14:31
The integer-power loop counts the exponent down as an int, so (-1)^n threw
OverflowException for |n| >= 2^31 although the result is always ±1. Answer
-1 by the parity of the power before the loop, as +1 already is.

Fixes #128

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JGKBe8wvU3P6jYj9MkNC69
…down

SonarCloud S3776 flagged Pow at cognitive complexity 21 (limit 15) once the
(-1)^n shortcut was added. The integer branch is now its own method; behaviour
is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JGKBe8wvU3P6jYj9MkNC69
@sonarqubecloud

sonarqubecloud Bot commented Oct 6, 2026

Copy link
Copy Markdown

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.

Pow(-1, n) throws OverflowException for any integer |n| ≥ 2^31, although the result is ±1

2 participants