← 输入框|github.com|刷新
Skip to content

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

Open

Description

@sambrossard

Mirror of upstream TheAlgorithms#7751, tracked on this fork for a course lab (no upstream contribution).

Description

com.thealgorithms.maths.Pow.pow(int a, int b) multiplies into a long without checking whether the result is representable, so it silently wraps on overflow.

Steps to reproduce

  1. Call Pow.pow(2, 63) -> returns Long.MIN_VALUE (expected 9223372036854775808, which exceeds Long.MAX_VALUE).
  2. Call Pow.pow(2, 64) -> returns 0.

Expected behavior

When the exact result cannot fit in a long, the method should detect it and throw ArithmeticException.

Test case

@Test
void throwsOnOverflow() {
    assertThrows(ArithmeticException.class, () -> Pow.pow(2, 63));
}

Activity

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions