001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     * 
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     * 
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.commons.lang3.math;
018    
019    import java.math.BigInteger;
020    
021    /**
022     * <p><code>Fraction</code> is a <code>Number</code> implementation that
023     * stores fractions accurately.</p>
024     *
025     * <p>This class is immutable, and interoperable with most methods that accept
026     * a <code>Number</code>.</p>
027     *
028     * @author Apache Software Foundation
029     * @author Travis Reeder
030     * @author Tim O'Brien
031     * @author Pete Gieser
032     * @author C. Scott Ananian
033     * @since 2.0
034     * @version $Id: Fraction.java 889215 2009-12-10 11:56:38Z bayard $
035     */
036    public final class Fraction extends Number implements Comparable<Fraction> {
037    
038        /**
039         * Required for serialization support. Lang version 2.0.
040         * 
041         * @see java.io.Serializable
042         */
043        private static final long serialVersionUID = 65382027393090L;
044    
045        /**
046         * <code>Fraction</code> representation of 0.
047         */
048        public static final Fraction ZERO = new Fraction(0, 1);
049        /**
050         * <code>Fraction</code> representation of 1.
051         */
052        public static final Fraction ONE = new Fraction(1, 1);
053        /**
054         * <code>Fraction</code> representation of 1/2.
055         */
056        public static final Fraction ONE_HALF = new Fraction(1, 2);
057        /**
058         * <code>Fraction</code> representation of 1/3.
059         */
060        public static final Fraction ONE_THIRD = new Fraction(1, 3);
061        /**
062         * <code>Fraction</code> representation of 2/3.
063         */
064        public static final Fraction TWO_THIRDS = new Fraction(2, 3);
065        /**
066         * <code>Fraction</code> representation of 1/4.
067         */
068        public static final Fraction ONE_QUARTER = new Fraction(1, 4);
069        /**
070         * <code>Fraction</code> representation of 2/4.
071         */
072        public static final Fraction TWO_QUARTERS = new Fraction(2, 4);
073        /**
074         * <code>Fraction</code> representation of 3/4.
075         */
076        public static final Fraction THREE_QUARTERS = new Fraction(3, 4);
077        /**
078         * <code>Fraction</code> representation of 1/5.
079         */
080        public static final Fraction ONE_FIFTH = new Fraction(1, 5);
081        /**
082         * <code>Fraction</code> representation of 2/5.
083         */
084        public static final Fraction TWO_FIFTHS = new Fraction(2, 5);
085        /**
086         * <code>Fraction</code> representation of 3/5.
087         */
088        public static final Fraction THREE_FIFTHS = new Fraction(3, 5);
089        /**
090         * <code>Fraction</code> representation of 4/5.
091         */
092        public static final Fraction FOUR_FIFTHS = new Fraction(4, 5);
093    
094    
095        /**
096         * The numerator number part of the fraction (the three in three sevenths).
097         */
098        private final int numerator;
099        /**
100         * The denominator number part of the fraction (the seven in three sevenths).
101         */
102        private final int denominator;
103    
104        /**
105         * Cached output hashCode (class is immutable).
106         */
107        private transient int hashCode = 0;
108        /**
109         * Cached output toString (class is immutable).
110         */
111        private transient String toString = null;
112        /**
113         * Cached output toProperString (class is immutable).
114         */
115        private transient String toProperString = null;
116    
117        /**
118         * <p>Constructs a <code>Fraction</code> instance with the 2 parts
119         * of a fraction Y/Z.</p>
120         *
121         * @param numerator  the numerator, for example the three in 'three sevenths'
122         * @param denominator  the denominator, for example the seven in 'three sevenths'
123         */
124        private Fraction(int numerator, int denominator) {
125            super();
126            this.numerator = numerator;
127            this.denominator = denominator;
128        }
129    
130        /**
131         * <p>Creates a <code>Fraction</code> instance with the 2 parts
132         * of a fraction Y/Z.</p>
133         *
134         * <p>Any negative signs are resolved to be on the numerator.</p>
135         *
136         * @param numerator  the numerator, for example the three in 'three sevenths'
137         * @param denominator  the denominator, for example the seven in 'three sevenths'
138         * @return a new fraction instance
139         * @throws ArithmeticException if the denomiator is <code>zero</code>
140         */
141        public static Fraction getFraction(int numerator, int denominator) {
142            if (denominator == 0) {
143                throw new ArithmeticException("The denominator must not be zero");
144            }
145            if (denominator < 0) {
146                if (numerator==Integer.MIN_VALUE ||
147                        denominator==Integer.MIN_VALUE) {
148                    throw new ArithmeticException("overflow: can't negate");
149                }
150                numerator = -numerator;
151                denominator = -denominator;
152            }
153            return new Fraction(numerator, denominator);
154        }
155    
156        /**
157         * <p>Creates a <code>Fraction</code> instance with the 3 parts
158         * of a fraction X Y/Z.</p>
159         *
160         * <p>The negative sign must be passed in on the whole number part.</p>
161         *
162         * @param whole  the whole number, for example the one in 'one and three sevenths'
163         * @param numerator  the numerator, for example the three in 'one and three sevenths'
164         * @param denominator  the denominator, for example the seven in 'one and three sevenths'
165         * @return a new fraction instance
166         * @throws ArithmeticException if the denomiator is <code>zero</code>
167         * @throws ArithmeticException if the denominator is negative
168         * @throws ArithmeticException if the numerator is negative
169         * @throws ArithmeticException if the resulting numerator exceeds 
170         *  <code>Integer.MAX_VALUE</code>
171         */
172        public static Fraction getFraction(int whole, int numerator, int denominator) {
173            if (denominator == 0) {
174                throw new ArithmeticException("The denominator must not be zero");
175            }
176            if (denominator < 0) {
177                throw new ArithmeticException("The denominator must not be negative");
178            }
179            if (numerator < 0) {
180                throw new ArithmeticException("The numerator must not be negative");
181            }
182            long numeratorValue;
183            if (whole < 0) {
184                numeratorValue = whole * (long)denominator - numerator;
185            } else {
186                numeratorValue = whole * (long)denominator + numerator;
187            }
188            if (numeratorValue < Integer.MIN_VALUE ||
189                    numeratorValue > Integer.MAX_VALUE)  {
190                throw new ArithmeticException("Numerator too large to represent as an Integer.");
191            }
192            return new Fraction((int) numeratorValue, denominator);
193        }
194    
195        /**
196         * <p>Creates a reduced <code>Fraction</code> instance with the 2 parts
197         * of a fraction Y/Z.</p>
198         *
199         * <p>For example, if the input parameters represent 2/4, then the created
200         * fraction will be 1/2.</p>
201         *
202         * <p>Any negative signs are resolved to be on the numerator.</p>
203         *
204         * @param numerator  the numerator, for example the three in 'three sevenths'
205         * @param denominator  the denominator, for example the seven in 'three sevenths'
206         * @return a new fraction instance, with the numerator and denominator reduced
207         * @throws ArithmeticException if the denominator is <code>zero</code>
208         */
209        public static Fraction getReducedFraction(int numerator, int denominator) {
210            if (denominator == 0) {
211                throw new ArithmeticException("The denominator must not be zero");
212            }
213            if (numerator==0) {
214                return ZERO; // normalize zero.
215            }
216            // allow 2^k/-2^31 as a valid fraction (where k>0)
217            if (denominator==Integer.MIN_VALUE && (numerator&1)==0) {
218                numerator/=2; denominator/=2;
219            }
220            if (denominator < 0) {
221                if (numerator==Integer.MIN_VALUE ||
222                        denominator==Integer.MIN_VALUE) {
223                    throw new ArithmeticException("overflow: can't negate");
224                }
225                numerator = -numerator;
226                denominator = -denominator;
227            }
228            // simplify fraction.
229            int gcd = greatestCommonDivisor(numerator, denominator);
230            numerator /= gcd;
231            denominator /= gcd;
232            return new Fraction(numerator, denominator);
233        }
234    
235        /**
236         * <p>Creates a <code>Fraction</code> instance from a <code>double</code> value.</p>
237         *
238         * <p>This method uses the <a href="http://archives.math.utk.edu/articles/atuyl/confrac/">
239         *  continued fraction algorithm</a>, computing a maximum of
240         *  25 convergents and bounding the denominator by 10,000.</p>
241         *
242         * @param value  the double value to convert
243         * @return a new fraction instance that is close to the value
244         * @throws ArithmeticException if <code>|value| > Integer.MAX_VALUE</code> 
245         *  or <code>value = NaN</code>
246         * @throws ArithmeticException if the calculated denominator is <code>zero</code>
247         * @throws ArithmeticException if the the algorithm does not converge
248         */
249        public static Fraction getFraction(double value) {
250            int sign = (value < 0 ? -1 : 1);
251            value = Math.abs(value);
252            if (value  > Integer.MAX_VALUE || Double.isNaN(value)) {
253                throw new ArithmeticException
254                    ("The value must not be greater than Integer.MAX_VALUE or NaN");
255            }
256            int wholeNumber = (int) value;
257            value -= wholeNumber;
258            
259            int numer0 = 0;  // the pre-previous
260            int denom0 = 1;  // the pre-previous
261            int numer1 = 1;  // the previous
262            int denom1 = 0;  // the previous
263            int numer2 = 0;  // the current, setup in calculation
264            int denom2 = 0;  // the current, setup in calculation
265            int a1 = (int) value;
266            int a2 = 0;
267            double x1 = 1;
268            double x2 = 0;
269            double y1 = value - a1;
270            double y2 = 0;
271            double delta1, delta2 = Double.MAX_VALUE;
272            double fraction;
273            int i = 1;
274    //        System.out.println("---");
275            do {
276                delta1 = delta2;
277                a2 = (int) (x1 / y1);
278                x2 = y1;
279                y2 = x1 - a2 * y1;
280                numer2 = a1 * numer1 + numer0;
281                denom2 = a1 * denom1 + denom0;
282                fraction = (double) numer2 / (double) denom2;
283                delta2 = Math.abs(value - fraction);
284    //            System.out.println(numer2 + " " + denom2 + " " + fraction + " " + delta2 + " " + y1);
285                a1 = a2;
286                x1 = x2;
287                y1 = y2;
288                numer0 = numer1;
289                denom0 = denom1;
290                numer1 = numer2;
291                denom1 = denom2;
292                i++;
293    //            System.out.println(">>" + delta1 +" "+ delta2+" "+(delta1 > delta2)+" "+i+" "+denom2);
294            } while ((delta1 > delta2) && (denom2 <= 10000) && (denom2 > 0) && (i < 25));
295            if (i == 25) {
296                throw new ArithmeticException("Unable to convert double to fraction");
297            }
298            return getReducedFraction((numer0 + wholeNumber * denom0) * sign, denom0);
299        }
300    
301        /**
302         * <p>Creates a Fraction from a <code>String</code>.</p>
303         *
304         * <p>The formats accepted are:</p>
305         *
306         * <ol>
307         *  <li><code>double</code> String containing a dot</li>
308         *  <li>'X Y/Z'</li>
309         *  <li>'Y/Z'</li>
310         *  <li>'X' (a simple whole number)</li>
311         * </ol>
312         * and a .</p>
313         *
314         * @param str  the string to parse, must not be <code>null</code>
315         * @return the new <code>Fraction</code> instance
316         * @throws IllegalArgumentException if the string is <code>null</code>
317         * @throws NumberFormatException if the number format is invalid
318         */
319        public static Fraction getFraction(String str) {
320            if (str == null) {
321                throw new IllegalArgumentException("The string must not be null");
322            }
323            // parse double format
324            int pos = str.indexOf('.');
325            if (pos >= 0) {
326                return getFraction(Double.parseDouble(str));
327            }
328    
329            // parse X Y/Z format
330            pos = str.indexOf(' ');
331            if (pos > 0) {
332                int whole = Integer.parseInt(str.substring(0, pos));
333                str = str.substring(pos + 1);
334                pos = str.indexOf('/');
335                if (pos < 0) {
336                    throw new NumberFormatException("The fraction could not be parsed as the format X Y/Z");
337                } else {
338                    int numer = Integer.parseInt(str.substring(0, pos));
339                    int denom = Integer.parseInt(str.substring(pos + 1));
340                    return getFraction(whole, numer, denom);
341                }
342            }
343    
344            // parse Y/Z format
345            pos = str.indexOf('/');
346            if (pos < 0) {
347                // simple whole number
348                return getFraction(Integer.parseInt(str), 1);
349            } else {
350                int numer = Integer.parseInt(str.substring(0, pos));
351                int denom = Integer.parseInt(str.substring(pos + 1));
352                return getFraction(numer, denom);
353            }
354        }
355    
356        // Accessors
357        //-------------------------------------------------------------------
358    
359        /**
360         * <p>Gets the numerator part of the fraction.</p>
361         *
362         * <p>This method may return a value greater than the denominator, an
363         * improper fraction, such as the seven in 7/4.</p>
364         *
365         * @return the numerator fraction part
366         */
367        public int getNumerator() {
368            return numerator;
369        }
370    
371        /**
372         * <p>Gets the denominator part of the fraction.</p>
373         *
374         * @return the denominator fraction part
375         */
376        public int getDenominator() {
377            return denominator;
378        }
379    
380        /**
381         * <p>Gets the proper numerator, always positive.</p>
382         *
383         * <p>An improper fraction 7/4 can be resolved into a proper one, 1 3/4.
384         * This method returns the 3 from the proper fraction.</p>
385         *
386         * <p>If the fraction is negative such as -7/4, it can be resolved into
387         * -1 3/4, so this method returns the positive proper numerator, 3.</p>
388         *
389         * @return the numerator fraction part of a proper fraction, always positive
390         */
391        public int getProperNumerator() {
392            return Math.abs(numerator % denominator);
393        }
394    
395        /**
396         * <p>Gets the proper whole part of the fraction.</p>
397         *
398         * <p>An improper fraction 7/4 can be resolved into a proper one, 1 3/4.
399         * This method returns the 1 from the proper fraction.</p>
400         *
401         * <p>If the fraction is negative such as -7/4, it can be resolved into
402         * -1 3/4, so this method returns the positive whole part -1.</p>
403         *
404         * @return the whole fraction part of a proper fraction, that includes the sign
405         */
406        public int getProperWhole() {
407            return numerator / denominator;
408        }
409    
410        // Number methods
411        //-------------------------------------------------------------------
412    
413        /**
414         * <p>Gets the fraction as an <code>int</code>. This returns the whole number
415         * part of the fraction.</p>
416         *
417         * @return the whole number fraction part
418         */
419        @Override
420        public int intValue() {
421            return numerator / denominator;
422        }
423    
424        /**
425         * <p>Gets the fraction as a <code>long</code>. This returns the whole number
426         * part of the fraction.</p>
427         *
428         * @return the whole number fraction part
429         */
430        @Override
431        public long longValue() {
432            return (long) numerator / denominator;
433        }
434    
435        /**
436         * <p>Gets the fraction as a <code>float</code>. This calculates the fraction
437         * as the numerator divided by denominator.</p>
438         *
439         * @return the fraction as a <code>float</code>
440         */
441        @Override
442        public float floatValue() {
443            return ((float) numerator) / ((float) denominator);
444        }
445    
446        /**
447         * <p>Gets the fraction as a <code>double</code>. This calculates the fraction
448         * as the numerator divided by denominator.</p>
449         *
450         * @return the fraction as a <code>double</code>
451         */
452        @Override
453        public double doubleValue() {
454            return ((double) numerator) / ((double) denominator);
455        }
456    
457        // Calculations
458        //-------------------------------------------------------------------
459    
460        /**
461         * <p>Reduce the fraction to the smallest values for the numerator and
462         * denominator, returning the result.</p>
463         * 
464         * <p>For example, if this fraction represents 2/4, then the result
465         * will be 1/2.</p>
466         *
467         * @return a new reduced fraction instance, or this if no simplification possible
468         */
469        public Fraction reduce() {
470            if (numerator == 0) {
471                return equals(ZERO) ? this : ZERO;
472            }
473            int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);
474            if (gcd == 1) {
475                return this;
476            }
477            return Fraction.getFraction(numerator / gcd, denominator / gcd);
478        }
479    
480        /**
481         * <p>Gets a fraction that is the inverse (1/fraction) of this one.</p>
482         * 
483         * <p>The returned fraction is not reduced.</p>
484         *
485         * @return a new fraction instance with the numerator and denominator
486         *         inverted.
487         * @throws ArithmeticException if the fraction represents zero.
488         */
489        public Fraction invert() {
490            if (numerator == 0) {
491                throw new ArithmeticException("Unable to invert zero.");
492            }
493            if (numerator==Integer.MIN_VALUE) {
494                throw new ArithmeticException("overflow: can't negate numerator");
495            }
496            if (numerator<0) {
497                return new Fraction(-denominator, -numerator);
498            } else {
499                return new Fraction(denominator, numerator);
500            }
501        }
502    
503        /**
504         * <p>Gets a fraction that is the negative (-fraction) of this one.</p>
505         *
506         * <p>The returned fraction is not reduced.</p>
507         *
508         * @return a new fraction instance with the opposite signed numerator
509         */
510        public Fraction negate() {
511            // the positive range is one smaller than the negative range of an int.
512            if (numerator==Integer.MIN_VALUE) {
513                throw new ArithmeticException("overflow: too large to negate");
514            }
515            return new Fraction(-numerator, denominator);
516        }
517    
518        /**
519         * <p>Gets a fraction that is the positive equivalent of this one.</p>
520         * <p>More precisely: <code>(fraction >= 0 ? this : -fraction)</code></p>
521         *
522         * <p>The returned fraction is not reduced.</p>
523         *
524         * @return <code>this</code> if it is positive, or a new positive fraction
525         *  instance with the opposite signed numerator
526         */
527        public Fraction abs() {
528            if (numerator >= 0) {
529                return this;
530            }
531            return negate();
532        }
533    
534        /**
535         * <p>Gets a fraction that is raised to the passed in power.</p>
536         *
537         * <p>The returned fraction is in reduced form.</p>
538         *
539         * @param power  the power to raise the fraction to
540         * @return <code>this</code> if the power is one, <code>ONE</code> if the power
541         * is zero (even if the fraction equals ZERO) or a new fraction instance 
542         * raised to the appropriate power
543         * @throws ArithmeticException if the resulting numerator or denominator exceeds
544         *  <code>Integer.MAX_VALUE</code>
545         */
546        public Fraction pow(int power) {
547            if (power == 1) {
548                return this;
549            } else if (power == 0) {
550                return ONE;
551            } else if (power < 0) {
552                if (power==Integer.MIN_VALUE) { // MIN_VALUE can't be negated.
553                    return this.invert().pow(2).pow(-(power/2));
554                }
555                return this.invert().pow(-power);
556            } else {
557                Fraction f = this.multiplyBy(this);
558                if ((power % 2) == 0) { // if even...
559                    return f.pow(power/2);
560                } else { // if odd...
561                    return f.pow(power/2).multiplyBy(this);
562                }
563            }
564        }
565    
566        /**
567         * <p>Gets the greatest common divisor of the absolute value of
568         * two numbers, using the "binary gcd" method which avoids
569         * division and modulo operations.  See Knuth 4.5.2 algorithm B.
570         * This algorithm is due to Josef Stein (1961).</p>
571         *
572         * @param u  a non-zero number
573         * @param v  a non-zero number
574         * @return the greatest common divisor, never zero
575         */
576        private static int greatestCommonDivisor(int u, int v) {
577            //if either op. is abs 0 or 1, return 1:
578            if (Math.abs(u) <= 1 || Math.abs(v) <= 1) {
579                return 1;
580            }
581            // keep u and v negative, as negative integers range down to
582            // -2^31, while positive numbers can only be as large as 2^31-1
583            // (i.e. we can't necessarily negate a negative number without
584            // overflow)
585            if (u>0) { u=-u; } // make u negative
586            if (v>0) { v=-v; } // make v negative
587            // B1. [Find power of 2]
588            int k=0;
589            while ((u&1)==0 && (v&1)==0 && k<31) { // while u and v are both even...
590                u/=2; v/=2; k++; // cast out twos.
591            }
592            if (k==31) {
593                throw new ArithmeticException("overflow: gcd is 2^31");
594            }
595            // B2. Initialize: u and v have been divided by 2^k and at least
596            //     one is odd.
597            int t = ((u&1)==1) ? v : -(u/2)/*B3*/;
598            // t negative: u was odd, v may be even (t replaces v)
599            // t positive: u was even, v is odd (t replaces u)
600            do {
601                /* assert u<0 && v<0; */
602                // B4/B3: cast out twos from t.
603                while ((t&1)==0) { // while t is even..
604                    t/=2; // cast out twos
605                }
606                // B5 [reset max(u,v)]
607                if (t>0) {
608                    u = -t;
609                } else {
610                    v = t;
611                }
612                // B6/B3. at this point both u and v should be odd.
613                t = (v - u)/2;
614                // |u| larger: t positive (replace u)
615                // |v| larger: t negative (replace v)
616            } while (t!=0);
617            return -u*(1<<k); // gcd is u*2^k
618        }
619    
620        // Arithmetic
621        //-------------------------------------------------------------------
622    
623        /** 
624         * Multiply two integers, checking for overflow.
625         * 
626         * @param x a factor
627         * @param y a factor
628         * @return the product <code>x*y</code>
629         * @throws ArithmeticException if the result can not be represented as
630         *                             an int
631         */
632        private static int mulAndCheck(int x, int y) {
633            long m = ((long)x)*((long)y);
634            if (m < Integer.MIN_VALUE ||
635                m > Integer.MAX_VALUE) {
636                throw new ArithmeticException("overflow: mul");
637            }
638            return (int)m;
639        }
640        
641        /**
642         *  Multiply two non-negative integers, checking for overflow.
643         * 
644         * @param x a non-negative factor
645         * @param y a non-negative factor
646         * @return the product <code>x*y</code>
647         * @throws ArithmeticException if the result can not be represented as
648         * an int
649         */
650        private static int mulPosAndCheck(int x, int y) {
651            /* assert x>=0 && y>=0; */
652            long m = ((long)x)*((long)y);
653            if (m > Integer.MAX_VALUE) {
654                throw new ArithmeticException("overflow: mulPos");
655            }
656            return (int)m;
657        }
658        
659        /** 
660         * Add two integers, checking for overflow.
661         * 
662         * @param x an addend
663         * @param y an addend
664         * @return the sum <code>x+y</code>
665         * @throws ArithmeticException if the result can not be represented as
666         * an int
667         */
668        private static int addAndCheck(int x, int y) {
669            long s = (long)x+(long)y;
670            if (s < Integer.MIN_VALUE ||
671                s > Integer.MAX_VALUE) {
672                throw new ArithmeticException("overflow: add");
673            }
674            return (int)s;
675        }
676        
677        /** 
678         * Subtract two integers, checking for overflow.
679         * 
680         * @param x the minuend
681         * @param y the subtrahend
682         * @return the difference <code>x-y</code>
683         * @throws ArithmeticException if the result can not be represented as
684         * an int
685         */
686        private static int subAndCheck(int x, int y) {
687            long s = (long)x-(long)y;
688            if (s < Integer.MIN_VALUE ||
689                s > Integer.MAX_VALUE) {
690                throw new ArithmeticException("overflow: add");
691            }
692            return (int)s;
693        }
694        
695        /**
696         * <p>Adds the value of this fraction to another, returning the result in reduced form.
697         * The algorithm follows Knuth, 4.5.1.</p>
698         *
699         * @param fraction  the fraction to add, must not be <code>null</code>
700         * @return a <code>Fraction</code> instance with the resulting values
701         * @throws IllegalArgumentException if the fraction is <code>null</code>
702         * @throws ArithmeticException if the resulting numerator or denominator exceeds
703         *  <code>Integer.MAX_VALUE</code>
704         */
705        public Fraction add(Fraction fraction) {
706            return addSub(fraction, true /* add */);
707        }
708    
709        /**
710         * <p>Subtracts the value of another fraction from the value of this one, 
711         * returning the result in reduced form.</p>
712         *
713         * @param fraction  the fraction to subtract, must not be <code>null</code>
714         * @return a <code>Fraction</code> instance with the resulting values
715         * @throws IllegalArgumentException if the fraction is <code>null</code>
716         * @throws ArithmeticException if the resulting numerator or denominator
717         *   cannot be represented in an <code>int</code>.
718         */
719        public Fraction subtract(Fraction fraction) {
720            return addSub(fraction, false /* subtract */);
721        }
722    
723        /** 
724         * Implement add and subtract using algorithm described in Knuth 4.5.1.
725         * 
726         * @param fraction the fraction to subtract, must not be <code>null</code>
727         * @param isAdd true to add, false to subtract
728         * @return a <code>Fraction</code> instance with the resulting values
729         * @throws IllegalArgumentException if the fraction is <code>null</code>
730         * @throws ArithmeticException if the resulting numerator or denominator
731         *   cannot be represented in an <code>int</code>.
732         */
733        private Fraction addSub(Fraction fraction, boolean isAdd) {
734            if (fraction == null) {
735                throw new IllegalArgumentException("The fraction must not be null");
736            }
737            // zero is identity for addition.
738            if (numerator == 0) {
739                return isAdd ? fraction : fraction.negate();
740            }
741            if (fraction.numerator == 0) {
742                return this;
743            }     
744            // if denominators are randomly distributed, d1 will be 1 about 61%
745            // of the time.
746            int d1 = greatestCommonDivisor(denominator, fraction.denominator);
747            if (d1==1) {
748                // result is ( (u*v' +/- u'v) / u'v')
749                int uvp = mulAndCheck(numerator, fraction.denominator);
750                int upv = mulAndCheck(fraction.numerator, denominator);
751                return new Fraction
752                    (isAdd ? addAndCheck(uvp, upv) : subAndCheck(uvp, upv),
753                     mulPosAndCheck(denominator, fraction.denominator));
754            }
755            // the quantity 't' requires 65 bits of precision; see knuth 4.5.1
756            // exercise 7.  we're going to use a BigInteger.
757            // t = u(v'/d1) +/- v(u'/d1)
758            BigInteger uvp = BigInteger.valueOf(numerator)
759                .multiply(BigInteger.valueOf(fraction.denominator/d1));
760            BigInteger upv = BigInteger.valueOf(fraction.numerator)
761                .multiply(BigInteger.valueOf(denominator/d1));
762            BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv);
763            // but d2 doesn't need extra precision because
764            // d2 = gcd(t,d1) = gcd(t mod d1, d1)
765            int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue();
766            int d2 = (tmodd1==0)?d1:greatestCommonDivisor(tmodd1, d1);
767    
768            // result is (t/d2) / (u'/d1)(v'/d2)
769            BigInteger w = t.divide(BigInteger.valueOf(d2));
770            if (w.bitLength() > 31) {
771                throw new ArithmeticException
772                    ("overflow: numerator too large after multiply");
773            }
774            return new Fraction
775                (w.intValue(),
776                 mulPosAndCheck(denominator/d1, fraction.denominator/d2));
777        }
778    
779        /**
780         * <p>Multiplies the value of this fraction by another, returning the 
781         * result in reduced form.</p>
782         *
783         * @param fraction  the fraction to multiply by, must not be <code>null</code>
784         * @return a <code>Fraction</code> instance with the resulting values
785         * @throws IllegalArgumentException if the fraction is <code>null</code>
786         * @throws ArithmeticException if the resulting numerator or denominator exceeds
787         *  <code>Integer.MAX_VALUE</code>
788         */
789        public Fraction multiplyBy(Fraction fraction) {
790            if (fraction == null) {
791                throw new IllegalArgumentException("The fraction must not be null");
792            }
793            if (numerator == 0 || fraction.numerator == 0) {
794                return ZERO;
795            }
796            // knuth 4.5.1
797            // make sure we don't overflow unless the result *must* overflow.
798            int d1 = greatestCommonDivisor(numerator, fraction.denominator);
799            int d2 = greatestCommonDivisor(fraction.numerator, denominator);
800            return getReducedFraction
801                (mulAndCheck(numerator/d1, fraction.numerator/d2),
802                 mulPosAndCheck(denominator/d2, fraction.denominator/d1));
803        }
804    
805        /**
806         * <p>Divide the value of this fraction by another.</p>
807         *
808         * @param fraction  the fraction to divide by, must not be <code>null</code>
809         * @return a <code>Fraction</code> instance with the resulting values
810         * @throws IllegalArgumentException if the fraction is <code>null</code>
811         * @throws ArithmeticException if the fraction to divide by is zero
812         * @throws ArithmeticException if the resulting numerator or denominator exceeds
813         *  <code>Integer.MAX_VALUE</code>
814         */
815        public Fraction divideBy(Fraction fraction) {
816            if (fraction == null) {
817                throw new IllegalArgumentException("The fraction must not be null");
818            }
819            if (fraction.numerator == 0) {
820                throw new ArithmeticException("The fraction to divide by must not be zero");
821            }
822            return multiplyBy(fraction.invert());
823        }
824    
825        // Basics
826        //-------------------------------------------------------------------
827    
828        /**
829         * <p>Compares this fraction to another object to test if they are equal.</p>.
830         *
831         * <p>To be equal, both values must be equal. Thus 2/4 is not equal to 1/2.</p>
832         *
833         * @param obj the reference object with which to compare
834         * @return <code>true</code> if this object is equal
835         */
836        @Override
837        public boolean equals(Object obj) {
838            if (obj == this) {
839                return true;
840            }
841            if (obj instanceof Fraction == false) {
842                return false;
843            }
844            Fraction other = (Fraction) obj;
845            return (getNumerator() == other.getNumerator() &&
846                    getDenominator() == other.getDenominator());
847        }
848    
849        /**
850         * <p>Gets a hashCode for the fraction.</p>
851         *
852         * @return a hash code value for this object
853         */
854        @Override
855        public int hashCode() {
856            if (hashCode == 0) {
857                // hashcode update should be atomic.
858                hashCode = 37 * (37 * 17 + getNumerator()) + getDenominator();
859            }
860            return hashCode;
861        }
862    
863        /**
864         * <p>Compares this object to another based on size.</p>
865         *
866         * <p>Note: this class has a natural ordering that is inconsistent
867         * with equals, because, for example, equals treats 1/2 and 2/4 as
868         * different, whereas compareTo treats them as equal.
869         *
870         * @param other  the object to compare to
871         * @return -1 if this is less, 0 if equal, +1 if greater
872         * @throws ClassCastException if the object is not a <code>Fraction</code>
873         * @throws NullPointerException if the object is <code>null</code>
874         */
875        public int compareTo(Fraction other) {
876            if (this==other) {
877                return 0;
878            }
879            if (numerator == other.numerator && denominator == other.denominator) {
880                return 0;
881            }
882    
883            // otherwise see which is less
884            long first = (long) numerator * (long) other.denominator;
885            long second = (long) other.numerator * (long) denominator;
886            if (first == second) {
887                return 0;
888            } else if (first < second) {
889                return -1;
890            } else {
891                return 1;
892            }
893        }
894    
895        /**
896         * <p>Gets the fraction as a <code>String</code>.</p>
897         *
898         * <p>The format used is '<i>numerator</i>/<i>denominator</i>' always.
899         *
900         * @return a <code>String</code> form of the fraction
901         */
902        @Override
903        public String toString() {
904            if (toString == null) {
905                toString = new StringBuilder(32)
906                    .append(getNumerator())
907                    .append('/')
908                    .append(getDenominator()).toString();
909            }
910            return toString;
911        }
912    
913        /**
914         * <p>Gets the fraction as a proper <code>String</code> in the format X Y/Z.</p>
915         *
916         * <p>The format used in '<i>wholeNumber</i> <i>numerator</i>/<i>denominator</i>'.
917         * If the whole number is zero it will be ommitted. If the numerator is zero,
918         * only the whole number is returned.</p>
919         *
920         * @return a <code>String</code> form of the fraction
921         */
922        public String toProperString() {
923            if (toProperString == null) {
924                if (numerator == 0) {
925                    toProperString = "0";
926                } else if (numerator == denominator) {
927                    toProperString = "1";
928                } else if (numerator == -1 * denominator) {
929                    toProperString = "-1";
930                } else if ((numerator>0?-numerator:numerator) < -denominator) {
931                    // note that we do the magnitude comparison test above with
932                    // NEGATIVE (not positive) numbers, since negative numbers
933                    // have a larger range.  otherwise numerator==Integer.MIN_VALUE
934                    // is handled incorrectly.
935                    int properNumerator = getProperNumerator();
936                    if (properNumerator == 0) {
937                        toProperString = Integer.toString(getProperWhole());
938                    } else {
939                        toProperString = new StringBuilder(32)
940                            .append(getProperWhole()).append(' ')
941                            .append(properNumerator).append('/')
942                            .append(getDenominator()).toString();
943                    }
944                } else {
945                    toProperString = new StringBuilder(32)
946                        .append(getNumerator()).append('/')
947                        .append(getDenominator()).toString();
948                }
949            }
950            return toProperString;
951        }
952    }