Class RationalNumber

java.lang.Object
it.unimi.di.prog2.s10.RationalNumber

public class RationalNumber extends Object
A rational number is an immutable number that can be expressed as the quotient or fraction \( p/q \) of two ints, a numerator \( p \) and a non-zero denominator \( q \).
  • Field Details

    • numerator

      public final int numerator
      The numerator.
    • denominator

      public final int denominator
      The denominator.
  • Constructor Details

    • RationalNumber

      public RationalNumber(long numerator, long denominator)
      Creates a new rational number.

      The rational number is reduced to minimum terms, so the arguments of this methods are allowed to be longs and the fraction will be created if and only if the numerator and the denominator, once reduced to minimum terms, are not too large to be represented as ints.

      Parameters:
      numerator - the numerator.
      denominator - the denominator.
      Throws:
      IllegalArgumentException - if denominator is zero.
      IllegalArgumentException - if the numerator or the denominator reduced to minimum terms are too large to be represented as ints.
    • RationalNumber

      public RationalNumber(int value)
      Creates a new integer number.
      Parameters:
      value - the value.
  • Method Details

    • gcd

      private long gcd(long a, long b)
      Computes the greatest common divisor of two numbers.
      Parameters:
      a - the first number.
      b - the second number.
      Returns:
      the greatest common divisor of a and b.
    • add

      public RationalNumber add(RationalNumber other)
      Returns the sum of this rational number and another one.
      Parameters:
      other - the other rational number.
      Returns:
      the sum of this rational number and other.
    • mul

      public RationalNumber mul(RationalNumber other)
      Returns the product of this rational number and another one.
      Parameters:
      other - the other rational number.
      Returns:
      the product of this rational number and other.
    • isInteger

      public boolean isInteger()
      Tells whether this rational number is an integer.
      Returns:
      true if this rational number is an integer, false otherwise.
    • isPositive

      public boolean isPositive()
      Tells whether this rational number is positive.
      Returns:
      true if this rational number is positive, false otherwise.
    • isZero

      public boolean isZero()
      Tells whether this rational number is equal to zero.
      Returns:
      true if this rational number is zero, false otherwise.
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • equals

      public boolean equals(Object obj)
      Overrides:
      equals in class Object
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object