Skip to content

fix: reduce ADTFraction to canonical form and avoid int overflow - #7801

Merged
DenizAltunkapan merged 2 commits into
TheAlgorithms:masterfrom
KTH1007:fix/adtfraction-normalization-overflow
Dec 6, 2026
Merged

DenizAltunkapan merged 2 commits into
TheAlgorithms:masterfrom
KTH1007:fix/adtfraction-normalization-overflow

Conversation

@KTH1007

@KTH1007 KTH1007 commented Dec 5, 2026

Copy link
Copy Markdown
Contributor
  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized it.
  • All filenames are in PascalCase.
  • All functions and variable names follow Java naming conventions.
  • All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
  • All new algorithms include a corresponding test class that validates their functionality.
  • All new code is formatted with clang-format -i --style=file path/to/your/file.java

Description

ADTFraction is a record, so equals() and hashCode() compare its two parts directly. The compact constructor only rejected a zero denominator and left the fraction in whatever shape the caller passed in. Equal fractions were therefore unequal objects, and a negative denominator produced values like 1/-2.

The arithmetic methods also multiplied the parts as int before any reduction. Two fractions with large but cancelable parts wrapped around even when the reduced result fits into an int easily.

Changes

  • The constructor reduces both parts by their greatest common divisor and keeps the sign in the numerator, so the denominator is always positive. new ADTFraction(2, 4) now equals new ADTFraction(1, 2), and new ADTFraction(1, -2) prints as -1/2.
  • plus() adds the fractions over the least common multiple of the denominators instead of their product.
  • times() cancels each numerator against the opposite denominator before multiplying.
  • Both methods compute in long. When a reduced result does not fit into an int, they throw ArithmeticException instead of returning a wrapped value.
  • Parts equal to Integer.MIN_VALUE are handled as long, so a denominator of Integer.MIN_VALUE is reduced and normalized whenever its canonical form is representable, and the constructor throws ArithmeticException when it is not, for example new ADTFraction(1, Integer.MIN_VALUE).
  • reciprocal() goes through the same path, so the reciprocal of zero still raises IllegalArgumentException and a reciprocal that cannot be represented raises ArithmeticException.

Tests

ADTFractionTest grew from 7 to 30 tests. The new tests cover reduction, sign normalization, equality and hash code of equivalent fractions, Integer.MIN_VALUE parts, sums and products with reducible parts, and the cases where the intermediate product or the final result really is too large for an int.

Run against the previous implementation, the new test class reports 19 failures and 1 error. With the change all 30 tests pass.

mvn test -Dtest=ADTFractionTest
mvn checkstyle:check
mvn spotbugs:check
mvn pmd:check

Fixes #7764

…rithmetic

The compact constructor only rejected a zero denominator, so mathematically
equal fractions were unequal objects (1/2 and 2/4), a negative denominator
printed as "1/-2", and plus() and times() multiplied the parts as ints
without cancelling, which overflowed even when the reduced result was small.

Divide both parts by their greatest common divisor and keep the sign in the
numerator, so the denominator is always positive. Build sums from the least
common multiple and products with cross cancellation in long, and raise an
ArithmeticException only when the reduced result really does not fit into an
int. Integer.MIN_VALUE parts are handled as long values, which keeps the sign
change and the absolute value out of the int range.

Add tests for reduction, sign normalization, equals/hashCode, the
Integer.MIN_VALUE corner cases and for sums and products that overflow when
the parts are multiplied without reduction.

Signed-off-by: TAEHEON KIM <104629952+KTH1007@users.noreply.github.com>
@codecov-commenter

codecov-commenter commented Dec 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.56098% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 83.01%. Comparing base (9918769) to head (01f7449).

Files with missing lines Patch % Lines
...main/java/com/thealgorithms/maths/ADTFraction.java 97.56% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #7801      +/-   ##
============================================
+ Coverage     82.99%   83.01%   +0.01%     
- Complexity     8689     8696       +7     
============================================
  Files           849      849              
  Lines         26549    26583      +34     
  Branches       5176     5179       +3     
============================================
+ Hits          22035    22068      +33     
  Misses         3726     3726              
- Partials        788      789       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@KTH1007
KTH1007 marked this pull request as ready for review December 5, 2026 20:41
@DenizAltunkapan
DenizAltunkapan enabled auto-merge (squash) December 6, 2026 09:17
@DenizAltunkapan
DenizAltunkapan merged commit b595fda into TheAlgorithms:master Dec 6, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] ADTFraction: Lack of fraction reduction causes equals()/hashCode() contract violations and integer overflow

3 participants