Class RationalNumber
java.lang.Object
it.unimi.di.prog2.s12.RationalNumber
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 Summary
FieldsModifier and TypeFieldDescriptionfinal intThe denominator.final intThe numerator. -
Constructor Summary
ConstructorsConstructorDescriptionRationalNumber(int value) Creates a new integer number.RationalNumber(long numerator, long denominator) Creates a new rational number. -
Method Summary
Modifier and TypeMethodDescriptionadd(RationalNumber other) Returns the sum of this rational number and another one.booleanprivate longgcd(long a, long b) Computes the greatest common divisor of two numbers.inthashCode()booleanTells whether this rational number is an integer.booleanTells whether this rational number is positive.booleanisZero()Tells whether this rational number is equal to zero.mul(RationalNumber other) Returns the product of this rational number and another one.toString()
-
Field Details
-
numerator
public final int numeratorThe numerator. -
denominator
public final int denominatorThe 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 asints.- Parameters:
numerator- the numerator.denominator- the denominator.- Throws:
IllegalArgumentException- ifdenominatoris zero.IllegalArgumentException- if the numerator or the denominator reduced to minimum terms are too large to be represented asints.
-
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
aandb.
-
add
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
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:
trueif this rational number is an integer,falseotherwise.
-
isPositive
public boolean isPositive()Tells whether this rational number is positive.- Returns:
trueif this rational number is positive,falseotherwise.
-
isZero
public boolean isZero()Tells whether this rational number is equal to zero.- Returns:
trueif this rational number is zero,falseotherwise.
-
toString
-
equals
-
hashCode
-