Skip to content

Fix ModPow edge cases and overflow issues - #1322

Merged
williamfiset merged 1 commit into
williamfiset:masterfrom
TarunJain04:fix-modpow-edge-cases
Nov 9, 2026
Merged

williamfiset merged 1 commit into
williamfiset:masterfrom
TarunJain04:fix-modpow-edge-cases

Conversation

@TarunJain04

@TarunJain04 TarunJain04 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #56

Edge Cases Fixed

  1. modPow(a, 0, 1) returned 1 instead of 0

    • The result now starts at 1 % mod, so a modulus of 1 gives 0.
  2. Overflow in base reduction

    • A long holds at most 2^63 − 1.
    • The overflow was in (a % mod) + mod, which can reach 2·mod − 1. That exceeds 2^63 − 1 only when mod > 2^62.
    • The base is now reduced with a %= mod first, and mod is added only if the result is negative.
  3. Long.MIN_VALUE exponent caused infinite recursion (StackOverflowError)

    • -Long.MIN_VALUE overflows and stays Long.MIN_VALUE (still negative).
    • So the recursive call modPow(modInv(a, mod), -n, mod) re-entered the n < 0 branch forever.
    • Negative exponents are now handled iteratively.
    • The loop uses n != 0 with >>>=, so the exponent is read as an unsigned 2^63.

Tests

Added tests in ModPowTest.java covering each of the three edge cases above.

@williamfiset
williamfiset merged commit da35c18 into williamfiset:master Nov 9, 2026
2 checks passed
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.

ModPow function broken

2 participants