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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
Verification:
Validated the fixes with a stress test using inputs that previously triggered overflows:
Fixes numerical stability issues in the math module for large inputs.