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 (
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 thei32range.math.hypot: Inputs are now cast tof64before the power operation (xf**2 + yf**2). This ensures the squaring happens in floating-point math, avoiding thei32ceiling.
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 returned37550.84).
Fixes numerical stability issues in the math module for large inputs.