◐ Shell
clean mode source ↗

Fix intermediate integer overflow in math.lcm and math.hypot by ekMartian · Pull Request #2880 · lcompilers/lpython

Fix intermediate overflows in lcm and hypot

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 + yf**2). 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.