Class Rational

  • All Implemented Interfaces:
    java.io.Serializable, java.lang.Comparable<Rational>

    public final class Rational
    extends java.lang.Number
    implements java.lang.Comparable<Rational>
    Represents a rational number with a long numerator and long denominator. Rational numbers are stored in reduced form with the sign stored with the numerator. Rationals are immutable.

    Adapted from sample code featured in "Intro to Programming in Java: An Interdisciplinary Approach" (Addison Wesley) by Robert Sedgewick and Kevin Wayne. Permission granted to redistribute under BSD license.

    Version:
    $Id: Rational.java,v 1.0 Nov 18, 2009 1:12:00 AM haraldk Exp$
    See Also:
    Serialized Form
    • Field Detail

      • numerator

        private final long numerator
      • denominator

        private final long denominator
    • Constructor Detail

      • Rational

        private Rational()
      • Rational

        public Rational​(long pNumber)
      • Rational

        public Rational​(long pNumerator,
                        long pDenominator)
    • Method Detail

      • gcd

        private static long gcd​(long m,
                                long n)
      • lcm

        private static long lcm​(long m,
                                long n)
      • numerator

        public long numerator()
      • denominator

        public long denominator()
      • intValue

        public int intValue()
        Specified by:
        intValue in class java.lang.Number
      • longValue

        public long longValue()
        Specified by:
        longValue in class java.lang.Number
      • floatValue

        public float floatValue()
        Specified by:
        floatValue in class java.lang.Number
      • doubleValue

        public double doubleValue()
        Specified by:
        doubleValue in class java.lang.Number
      • compareTo

        public int compareTo​(Rational pOther)
        Specified by:
        compareTo in interface java.lang.Comparable<Rational>
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class java.lang.Object
      • equals

        public boolean equals​(java.lang.Object pOther)
        Overrides:
        equals in class java.lang.Object
      • toString

        public java.lang.String toString()
        Overrides:
        toString in class java.lang.Object
      • reciprocal

        public Rational reciprocal()