Prevent integer overflow in AreSame square comparison - #129
Merged
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.
Motivation
AreSame.compsquaredintvalues usingi * i, which silently overflows for |i| > 46340 and can make the comparison return incorrect true results.intinputs by avoiding wrapped 32-bit multiplication results.Description
mapToLong(i -> (long) i * i)when squaring the first array so the multiplication is performed in 64-bit arithmetic before sorting and comparison.longviamapToLong(i -> i)so both sides are compared aslong[]values and overflowedintsquares cannot be accepted.rejectsOverflowedSquaresinAreSameTestthat assertscomp(new int[]{46341}, new int[]{-2147479015})andcomp(new int[]{Integer.MIN_VALUE}, new int[]{0})return false.Testing
mvn -Dtest=AreSameTest testand the test suite executed the updated tests withTests run: 2, Failures: 0, Errors: 0indicating success.git diff --checklocally to validate the workspace diff contains only the intended changes and reported no whitespace or diff-check issues.Codex Task