Fix intermediate integer overflow in math.lcm and math.hypot#2881
Open
ekMartian wants to merge 1 commit intolcompilers:mainfrom
Open
Fix intermediate integer overflow in math.lcm and math.hypot#2881ekMartian wants to merge 1 commit intolcompilers:mainfrom
ekMartian wants to merge 1 commit intolcompilers:mainfrom
Conversation
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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$2^{31}-1$ ).
lcmandhypotfunctions were returning incorrect results for largeri32inputs 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, wherea*bwas 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.0 + yf**2.0). 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:
120000(previously returned-94749).100000.0(previously returned37550.84).Fixes numerical stability issues in the math module for large inputs.