| 1 | package com.thealgorithms.maths; |
| 2 | |
| 3 | public record ADTFraction(int numerator, int denominator) { |
| 4 | /** |
| 5 | * Initializes a newly created {@code ADTFraction} object so that it represents |
| 6 | * a fraction with the {@code numerator} and {@code denominator} provided as arguments. |
| 7 | * |
| 8 | * @param numerator The fraction numerator |
| 9 | * @param denominator The fraction denominator |
| 10 | */ |
| 11 | public ADTFraction { |
| 12 | if (denominator == 0) { |
| 13 | throw new IllegalArgumentException("Denominator cannot be 0"); |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * Add two fractions. |
| 19 | * |
| 20 | * @param fraction the {@code ADTFraction} to add |
| 21 | * @return A new {@code ADTFraction} containing the result of the operation |
| 22 | */ |
| 23 | public ADTFraction plus(ADTFraction fraction) { |
| 24 | var numerator = this.denominator * fraction.numerator + this.numerator * fraction.denominator; |
| 25 | var denominator = this.denominator * fraction.denominator; |
| 26 | return new ADTFraction(numerator, denominator); |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Multiply fraction by a number. |
| 31 | * |
| 32 | * @param number the number to multiply |
| 33 | * @return A new {@code ADTFraction} containing the result of the operation |
| 34 | */ |
| 35 | public ADTFraction times(int number) { |
| 36 | return times(new ADTFraction(number, 1)); |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Multiply two fractions. |
| 41 | * |
| 42 | * @param fraction the {@code ADTFraction} to multiply |
| 43 | * @return A new {@code ADTFraction} containing the result of the operation |
| 44 | */ |
| 45 | public ADTFraction times(ADTFraction fraction) { |
| 46 | var numerator = this.numerator * fraction.numerator; |
| 47 | var denominator = this.denominator * fraction.denominator; |
| 48 | return new ADTFraction(numerator, denominator); |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Generates the reciprocal of the fraction. |
| 53 | * |
| 54 | * @return A new {@code ADTFraction} with the {@code numerator} and {@code denominator} switched |
| 55 | */ |
| 56 | public ADTFraction reciprocal() { |
| 57 | return new ADTFraction(this.denominator, this.numerator); |
| 58 | } |
| 59 | |
| 60 | /** |
nothing calls this directly
no outgoing calls
no test coverage detected