Skip to content

Comments

Fix intermediate integer overflow in math.lcm and math.hypot#2881

Open
ekMartian wants to merge 1 commit intolcompilers:mainfrom
ekMartian:fix/lcm-hypot-v2
Open

Fix intermediate integer overflow in math.lcm and math.hypot#2881
ekMartian wants to merge 1 commit intolcompilers:mainfrom
ekMartian:fix/lcm-hypot-v2

Conversation

@ekMartian
Copy link

The lcm and hypot functions were returning incorrect results for larger i32 inputs due to intermediate overflows. This PR ensures that calculations remain within valid ranges even when intermediate values exceed the 32-bit signed integer limit ($2^{31}-1$).

Implementation Details:

  • math.lcm: Switched the order of operations to (a // gcd(a, b)) * b (unlike previously, where a*b was happening first). Dividing by the GCD first prevents the intermediate product from overflowing the i32 range.
  • math.hypot: Inputs are now cast to f64 before the power operation (xf**2.0 + yf**2.0). This ensures the squaring happens in floating-point math, avoiding the i32 ceiling.

Verification:

Validated the fixes with a stress test using inputs that previously triggered overflows:

  • lcm(60000, 40000): Correctly returns 120000 (previously returned -94749).
  • hypot(60000, 80000): Correctly returns 100000.0 (previously returned 37550.84).

Fixes numerical stability issues in the math module for large inputs.

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.

1 participant