Skip to content

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

Open

Description

@Prasad-Pitke

Description

com.thealgorithms.maths.Pow.pow(int a, int b) multiplies into a long without checking whether the result is representable. For example, Pow.pow(2, 63) mathematically equals 9223372036854775808, which is greater than Long.MAX_VALUE, but Java long overflow causes the method to return Long.MIN_VALUE. That is a plausible-looking but incorrect result for a utility documented as computing a power and returning a long.

Steps to reproduce

  1. Call Pow.pow(2, 63) (or Pow.pow(2, 64)).
  2. Observe the returned value: Long.MIN_VALUE for the first call, and 0 for the second, due to overflow wrapping.

Excepted behavior

When the exact result cannot fit in a long, the method should detect overflow and report it (for example, by throwing ArithmeticException), or explicitly document wraparound as its intended behavior.

Screenshots

No response

Additional context

No response

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions