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 */
017package org.apache.commons.numbers.fraction;
018
019import java.io.Serializable;
020import java.math.BigDecimal;
021import java.math.BigInteger;
022import java.math.RoundingMode;
023import java.util.Objects;
024import org.apache.commons.numbers.core.NativeOperators;
025
026/**
027 * Representation of a rational number using arbitrary precision.
028 *
029 * <p>The number is expressed as the quotient {@code p/q} of two {@link BigInteger}s,
030 * a numerator {@code p} and a non-zero denominator {@code q}.
031 *
032 * <p>This class is immutable.
033 *
034 * <a href="https://en.wikipedia.org/wiki/Rational_number">Rational number</a>
035 */
036public final class BigFraction
037    extends Number
038    implements Comparable<BigFraction>,
039               NativeOperators<BigFraction>,
040               Serializable {
041    /** A fraction representing "0". */
042    public static final BigFraction ZERO = new BigFraction(BigInteger.ZERO);
043
044    /** A fraction representing "1". */
045    public static final BigFraction ONE = new BigFraction(BigInteger.ONE);
046
047    /** Serializable version identifier. */
048    private static final long serialVersionUID = 20190701L;
049
050    /** The default iterations used for convergence. */
051    private static final int DEFAULT_MAX_ITERATIONS = 100;
052
053    /** Message for non-finite input double argument to factory constructors. */
054    private static final String NOT_FINITE = "Not finite: ";
055
056    /** The overflow limit for conversion from a double (2^31). */
057    private static final long OVERFLOW = 1L << 31;
058
059    /** The numerator of this fraction reduced to lowest terms. */
060    private final BigInteger numerator;
061
062    /** The denominator of this fraction reduced to lowest terms. */
063    private final BigInteger denominator;
064
065    /**
066     * Private constructor: Instances are created using factory methods.
067     *
068     * <p>This constructor should only be invoked when the fraction is known
069     * to be non-zero; otherwise use {@link #ZERO}. This avoids creating
070     * the zero representation {@code 0 / -1}.
071     *
072     * @param num Numerator, must not be {@code null}.
073     * @param den Denominator, must not be {@code null}.
074     * @throws ArithmeticException if the denominator is zero.
075     */
076    private BigFraction(BigInteger num, BigInteger den) {
077        if (den.signum() == 0) {
078            throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
079        }
080
081        // reduce numerator and denominator by greatest common denominator
082        final BigInteger gcd = num.gcd(den);
083        if (BigInteger.ONE.compareTo(gcd) < 0) {
084            numerator = num.divide(gcd);
085            denominator = den.divide(gcd);
086        } else {
087            numerator = num;
088            denominator = den;
089        }
090    }
091
092    /**
093     * Private constructor: Instances are created using factory methods.
094     *
095     * <p>This sets the denominator to 1.
096     *
097     * @param num Numerator (must not be null).
098     */
099    private BigFraction(BigInteger num) {
100        numerator = num;
101        denominator = BigInteger.ONE;
102    }
103
104    /**
105     * Create a fraction given the double value and either the maximum
106     * error allowed or the maximum number of denominator digits.
107     *
108     * <p>
109     * NOTE: This method is called with:
110     * </p>
111     * <ul>
112     *  <li>EITHER a valid epsilon value and the maxDenominator set to
113     *      Integer.MAX_VALUE (that way the maxDenominator has no effect)</li>
114     *  <li>OR a valid maxDenominator value and the epsilon value set to
115     *      zero (that way epsilon only has effect if there is an exact
116     *      match before the maxDenominator value is reached).</li>
117     * </ul>
118     * <p>
119     * It has been done this way so that the same code can be reused for
120     * both scenarios. However this could be confusing to users if it
121     * were part of the public API and this method should therefore remain
122     * PRIVATE.
123     * </p>
124     *
125     * <p>
126     * See JIRA issue ticket MATH-181 for more details:
127     *     https://issues.apache.org/jira/browse/MATH-181
128     * </p>
129     *
130     * @param value Value to convert to a fraction.
131     * @param epsilon Maximum error allowed.
132     * The resulting fraction is within {@code epsilon} of {@code value},
133     * in absolute terms.
134     * @param maxDenominator Maximum denominator value allowed.
135     * @param maxIterations Maximum number of convergents.
136     * @return a new instance.
137     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
138     * @throws ArithmeticException if the continued fraction failed to converge.
139     */
140    private static BigFraction from(final double value,
141                                    final double epsilon,
142                                    final int maxDenominator,
143                                    final int maxIterations) {
144        if (!Double.isFinite(value)) {
145            throw new IllegalArgumentException(NOT_FINITE + value);
146        }
147        if (value == 0) {
148            return ZERO;
149        }
150
151        // Remove sign, this is restored at the end.
152        // (Assumes the value is not zero and thus signum(value) is not zero).
153        final double absValue = Math.abs(value);
154        double r0 = absValue;
155        long a0 = (long) Math.floor(r0);
156        if (a0 > OVERFLOW) {
157            throw new FractionException(FractionException.ERROR_CONVERSION_OVERFLOW, value, a0, 1);
158        }
159
160        // check for (almost) integer arguments, which should not go to iterations.
161        if (r0 - a0 <= epsilon) {
162            // Restore the sign.
163            if (value < 0) {
164                a0 = -a0;
165            }
166            return new BigFraction(BigInteger.valueOf(a0));
167        }
168
169        // Support 2^31 as maximum denominator.
170        // This is negative as an integer so convert to long.
171        final long maxDen = Math.abs((long) maxDenominator);
172
173        long p0 = 1;
174        long q0 = 0;
175        long p1 = a0;
176        long q1 = 1;
177
178        long p2;
179        long q2;
180
181        int n = 0;
182        boolean stop = false;
183        do {
184            ++n;
185            final double r1 = 1.0 / (r0 - a0);
186            final long a1 = (long) Math.floor(r1);
187            p2 = (a1 * p1) + p0;
188            q2 = (a1 * q1) + q0;
189            if (Long.compareUnsigned(p2, OVERFLOW) > 0 ||
190                Long.compareUnsigned(q2, OVERFLOW) > 0) {
191                // In maxDenominator mode, fall-back to the previous valid fraction.
192                if (epsilon == 0) {
193                    p2 = p1;
194                    q2 = q1;
195                    break;
196                }
197                throw new FractionException(FractionException.ERROR_CONVERSION_OVERFLOW, value, p2, q2);
198            }
199
200            final double convergent = (double) p2 / q2;
201            if (n < maxIterations &&
202                Math.abs(convergent - absValue) > epsilon &&
203                q2 < maxDen) {
204                p0 = p1;
205                p1 = p2;
206                q0 = q1;
207                q1 = q2;
208                a0 = a1;
209                r0 = r1;
210            } else {
211                stop = true;
212            }
213        } while (!stop);
214
215        if (n >= maxIterations) {
216            throw new FractionException(FractionException.ERROR_CONVERSION, value, maxIterations);
217        }
218
219        // Use p2 / q2 or p1 / q1 if q2 has grown too large in maxDenominator mode
220        long num;
221        final long den;
222        if (q2 <= maxDen) {
223            num = p2;
224            den = q2;
225        } else {
226            num = p1;
227            den = q1;
228        }
229
230        // Restore the sign.
231        if (Math.signum(num) * Math.signum(den) != Math.signum(value)) {
232            num = -num;
233        }
234
235        return new BigFraction(BigInteger.valueOf(num),
236                               BigInteger.valueOf(den));
237    }
238
239    /**
240     * Create a fraction given the double value.
241     * <p>
242     * This factory method behaves <em>differently</em> to the method
243     * {@link #from(double, double, int)}. It converts the double value
244     * exactly, considering its internal bits representation. This works for all
245     * values except NaN and infinities and does not requires any loop or
246     * convergence threshold.
247     * </p>
248     * <p>
249     * Since this conversion is exact and since double numbers are sometimes
250     * approximated, the fraction created may seem strange in some cases. For example,
251     * calling {@code from(1.0 / 3.0)} does <em>not</em> create
252     * the fraction \( \frac{1}{3} \), but the fraction \( \frac{6004799503160661}{18014398509481984} \)
253     * because the double number passed to the method is not exactly \( \frac{1}{3} \)
254     * (which cannot be represented exactly in IEEE754).
255     * </p>
256     *
257     * @param value Value to convert to a fraction.
258     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
259     * @return a new instance.
260     *
261     * @see #from(double,double,int)
262     */
263    public static BigFraction from(final double value) {
264        if (!Double.isFinite(value)) {
265            throw new IllegalArgumentException(NOT_FINITE + value);
266        }
267        if (value == 0) {
268            return ZERO;
269        }
270
271        final long bits = Double.doubleToLongBits(value);
272        final long sign = bits & 0x8000000000000000L;
273        final long exponent = bits & 0x7ff0000000000000L;
274        final long mantissa = bits & 0x000fffffffffffffL;
275
276        // Compute m and k such that value = m * 2^k
277        long m;
278        int k;
279
280        if (exponent == 0) {
281            // Subnormal number, the effective exponent bias is 1022, not 1023.
282            // Note: mantissa is never zero as that case has been eliminated.
283            m = mantissa;
284            k = -1074;
285        } else {
286            // Normalized number: Add the implicit most significant bit.
287            m = mantissa | 0x0010000000000000L;
288            k = ((int) (exponent >> 52)) - 1075; // Exponent bias is 1023.
289        }
290        if (sign != 0) {
291            m = -m;
292        }
293        while ((m & 0x001ffffffffffffeL) != 0 &&
294               (m & 0x1) == 0) {
295            m >>= 1;
296            ++k;
297        }
298
299        return k < 0 ?
300            new BigFraction(BigInteger.valueOf(m),
301                            BigInteger.ZERO.flipBit(-k)) :
302            new BigFraction(BigInteger.valueOf(m).multiply(BigInteger.ZERO.flipBit(k)),
303                            BigInteger.ONE);
304    }
305
306    /**
307     * Create a fraction given the double value and maximum error allowed.
308     * <p>
309     * References:
310     * <ul>
311     * <li><a href="https://mathworld.wolfram.com/ContinuedFraction.html">
312     * Continued Fraction</a> equations (11) and (22)-(26)</li>
313     * </ul>
314     *
315     * @param value Value to convert to a fraction.
316     * @param epsilon Maximum error allowed. The resulting fraction is within
317     * {@code epsilon} of {@code value}, in absolute terms.
318     * @param maxIterations Maximum number of convergents.
319     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite;
320     * {@code epsilon} is not positive; or {@code maxIterations < 1}.
321     * @throws ArithmeticException if the continued fraction failed to converge.
322     * @return a new instance.
323     */
324    public static BigFraction from(final double value,
325                                   final double epsilon,
326                                   final int maxIterations) {
327        if (maxIterations < 1) {
328            throw new IllegalArgumentException("Max iterations must be strictly positive: " + maxIterations);
329        }
330        if (epsilon >= 0) {
331            return from(value, epsilon, Integer.MIN_VALUE, maxIterations);
332        }
333        throw new IllegalArgumentException("Epsilon must be positive: " + maxIterations);
334    }
335
336    /**
337     * Create a fraction given the double value and maximum denominator.
338     *
339     * <p>
340     * References:
341     * <ul>
342     * <li><a href="https://mathworld.wolfram.com/ContinuedFraction.html">
343     * Continued Fraction</a> equations (11) and (22)-(26)</li>
344     * </ul>
345     *
346     * <p>Note: The magnitude of the {@code maxDenominator} is used allowing use of
347     * {@link Integer#MIN_VALUE} for a supported maximum denominator of 2<sup>31</sup>.
348     *
349     * @param value Value to convert to a fraction.
350     * @param maxDenominator Maximum allowed value for denominator.
351     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite
352     * or {@code maxDenominator} is zero.
353     * @throws ArithmeticException if the continued fraction failed to converge.
354     * @return a new instance.
355     */
356    public static BigFraction from(final double value,
357                                   final int maxDenominator) {
358        if (maxDenominator == 0) {
359            // Re-use the zero denominator message
360            throw new IllegalArgumentException(FractionException.ERROR_ZERO_DENOMINATOR);
361        }
362        return from(value, 0, maxDenominator, DEFAULT_MAX_ITERATIONS);
363    }
364
365    /**
366     * Create a fraction given the numerator. The denominator is {@code 1}.
367     *
368     * @param num
369     *            the numerator.
370     * @return a new instance.
371     */
372    public static BigFraction of(final int num) {
373        if (num == 0) {
374            return ZERO;
375        }
376        return new BigFraction(BigInteger.valueOf(num));
377    }
378
379    /**
380     * Create a fraction given the numerator. The denominator is {@code 1}.
381     *
382     * @param num Numerator.
383     * @return a new instance.
384     */
385    public static BigFraction of(final long num) {
386        if (num == 0) {
387            return ZERO;
388        }
389        return new BigFraction(BigInteger.valueOf(num));
390    }
391
392    /**
393     * Create a fraction given the numerator. The denominator is {@code 1}.
394     *
395     * @param num Numerator.
396     * @return a new instance.
397     * @throws NullPointerException if numerator is null.
398     */
399    public static BigFraction of(final BigInteger num) {
400        Objects.requireNonNull(num, "numerator");
401        if (num.signum() == 0) {
402            return ZERO;
403        }
404        return new BigFraction(num);
405    }
406
407    /**
408     * Create a fraction given the numerator and denominator.
409     * The fraction is reduced to lowest terms.
410     *
411     * @param num Numerator.
412     * @param den Denominator.
413     * @return a new instance.
414     * @throws ArithmeticException if {@code den} is zero.
415     */
416    public static BigFraction of(final int num, final int den) {
417        if (num == 0) {
418            return ZERO;
419        }
420        return new BigFraction(BigInteger.valueOf(num), BigInteger.valueOf(den));
421    }
422
423    /**
424     * Create a fraction given the numerator and denominator.
425     * The fraction is reduced to lowest terms.
426     *
427     * @param num Numerator.
428     * @param den Denominator.
429     * @return a new instance.
430     * @throws ArithmeticException if {@code den} is zero.
431     */
432    public static BigFraction of(final long num, final long den) {
433        if (num == 0) {
434            return ZERO;
435        }
436        return new BigFraction(BigInteger.valueOf(num), BigInteger.valueOf(den));
437    }
438
439    /**
440     * Create a fraction given the numerator and denominator.
441     * The fraction is reduced to lowest terms.
442     *
443     * @param num Numerator.
444     * @param den Denominator.
445     * @return a new instance.
446     * @throws NullPointerException if numerator or denominator are null.
447     * @throws ArithmeticException if the denominator is zero.
448     */
449    public static BigFraction of(final BigInteger num, final BigInteger den) {
450        if (num.signum() == 0) {
451            return ZERO;
452        }
453        return new BigFraction(num, den);
454    }
455
456    /**
457     * Returns a {@code BigFraction} instance representing the specified string {@code s}.
458     *
459     * <p>If {@code s} is {@code null}, then a {@code NullPointerException} is thrown.
460     *
461     * <p>The string must be in a format compatible with that produced by
462     * {@link #toString() BigFraction.toString()}.
463     * The format expects an integer optionally followed by a {@code '/'} character and
464     * and second integer. Leading and trailing spaces are allowed around each numeric part.
465     * Each numeric part is parsed using {@link BigInteger#BigInteger(String)}. The parts
466     * are interpreted as the numerator and optional denominator of the fraction. If absent
467     * the denominator is assumed to be "1".
468     *
469     * <p>Examples of valid strings and the equivalent {@code BigFraction} are shown below:
470     *
471     * <pre>
472     * "0"                 = BigFraction.of(0)
473     * "42"                = BigFraction.of(42)
474     * "0 / 1"             = BigFraction.of(0, 1)
475     * "1 / 3"             = BigFraction.of(1, 3)
476     * "-4 / 13"           = BigFraction.of(-4, 13)</pre>
477     *
478     * <p>Note: The fraction is returned in reduced form and the numerator and denominator
479     * may not match the values in the input string. For this reason the result of
480     * {@code BigFraction.parse(s).toString().equals(s)} may not be {@code true}.
481     *
482     * @param s String representation.
483     * @return an instance.
484     * @throws NullPointerException if the string is null.
485     * @throws NumberFormatException if the string does not contain a parsable fraction.
486     * @see BigInteger#BigInteger(String)
487     * @see #toString()
488     */
489    public static BigFraction parse(String s) {
490        final String stripped = s.replace(",", "");
491        final int slashLoc = stripped.indexOf('/');
492        // if no slash, parse as single number
493        if (slashLoc == -1) {
494            return of(new BigInteger(stripped.trim()));
495        }
496        final BigInteger num = new BigInteger(stripped.substring(0, slashLoc).trim());
497        final BigInteger denom = new BigInteger(stripped.substring(slashLoc + 1).trim());
498        return of(num, denom);
499    }
500
501    @Override
502    public BigFraction zero() {
503        return ZERO;
504    }
505
506    /**
507     * {@inheritDoc}
508     *
509     * @since 1.2
510     */
511    @Override
512    public boolean isZero() {
513        return numerator.signum() == 0;
514    }
515
516    @Override
517    public BigFraction one() {
518        return ONE;
519    }
520
521    /**
522     * {@inheritDoc}
523     *
524     * @since 1.2
525     */
526    @Override
527    public boolean isOne() {
528        return numerator.equals(denominator);
529    }
530
531    /**
532     * Access the numerator as a {@code BigInteger}.
533     *
534     * @return the numerator as a {@code BigInteger}.
535     */
536    public BigInteger getNumerator() {
537        return numerator;
538    }
539
540    /**
541     * Access the numerator as an {@code int}.
542     *
543     * @return the numerator as an {@code int}.
544     */
545    public int getNumeratorAsInt() {
546        return numerator.intValue();
547    }
548
549    /**
550     * Access the numerator as a {@code long}.
551     *
552     * @return the numerator as a {@code long}.
553     */
554    public long getNumeratorAsLong() {
555        return numerator.longValue();
556    }
557
558    /**
559     * Access the denominator as a {@code BigInteger}.
560     *
561     * @return the denominator as a {@code BigInteger}.
562     */
563    public BigInteger getDenominator() {
564        return denominator;
565    }
566
567    /**
568     * Access the denominator as an {@code int}.
569     *
570     * @return the denominator as an {@code int}.
571     */
572    public int getDenominatorAsInt() {
573        return denominator.intValue();
574    }
575
576    /**
577     * Access the denominator as a {@code long}.
578     *
579     * @return the denominator as a {@code long}.
580     */
581    public long getDenominatorAsLong() {
582        return denominator.longValue();
583    }
584
585    /**
586     * Retrieves the sign of this fraction.
587     *
588     * @return -1 if the value is strictly negative, 1 if it is strictly
589     * positive, 0 if it is 0.
590     */
591    public int signum() {
592        return numerator.signum() * denominator.signum();
593    }
594
595    /**
596     * Returns the absolute value of this fraction.
597     *
598     * @return the absolute value.
599     */
600    public BigFraction abs() {
601        return signum() >= 0 ?
602            this :
603            negate();
604    }
605
606    @Override
607    public BigFraction negate() {
608        return new BigFraction(numerator.negate(), denominator);
609    }
610
611    /**
612     * {@inheritDoc}
613     *
614     * <p>Raises an exception if the fraction is equal to zero.
615     *
616     * @throws ArithmeticException if the current numerator is {@code zero}
617     */
618    @Override
619    public BigFraction reciprocal() {
620        return new BigFraction(denominator, numerator);
621    }
622
623    /**
624     * Returns the {@code double} value closest to this fraction.
625     *
626     * @return the fraction as a {@code double}.
627     */
628    @Override
629    public double doubleValue() {
630        return Double.longBitsToDouble(toFloatingPointBits(11, 52));
631    }
632
633    /**
634     * Returns the {@code float} value closest to this fraction.
635     *
636     * @return the fraction as a {@code double}.
637     */
638    @Override
639    public float floatValue() {
640        return Float.intBitsToFloat((int) toFloatingPointBits(8, 23));
641    }
642
643    /**
644     * Returns the whole number part of the fraction.
645     *
646     * @return the largest {@code int} value that is not larger than this fraction.
647     */
648    @Override
649    public int intValue() {
650        return numerator.divide(denominator).intValue();
651    }
652
653    /**
654     * Returns the whole number part of the fraction.
655     *
656     * @return the largest {@code long} value that is not larger than this fraction.
657     */
658    @Override
659    public long longValue() {
660        return numerator.divide(denominator).longValue();
661    }
662
663    /**
664     * Returns the {@code BigDecimal} representation of this fraction.
665     * This calculates the fraction as numerator divided by denominator.
666     *
667     * @return the fraction as a {@code BigDecimal}.
668     * @throws ArithmeticException
669     *             if the exact quotient does not have a terminating decimal
670     *             expansion.
671     * @see BigDecimal
672     */
673    public BigDecimal bigDecimalValue() {
674        return new BigDecimal(numerator).divide(new BigDecimal(denominator));
675    }
676
677    /**
678     * Returns the {@code BigDecimal} representation of this fraction.
679     * This calculates the fraction as numerator divided by denominator
680     * following the passed rounding mode.
681     *
682     * @param roundingMode Rounding mode to apply.
683     * @return the fraction as a {@code BigDecimal}.
684     * @see BigDecimal
685     */
686    public BigDecimal bigDecimalValue(RoundingMode roundingMode) {
687        return new BigDecimal(numerator).divide(new BigDecimal(denominator), roundingMode);
688    }
689
690    /**
691     * Returns the {@code BigDecimal} representation of this fraction.
692     * This calculates the fraction as numerator divided by denominator
693     * following the passed scale and rounding mode.
694     *
695     * @param scale
696     *            scale of the {@code BigDecimal} quotient to be returned.
697     *            see {@link BigDecimal} for more information.
698     * @param roundingMode Rounding mode to apply.
699     * @return the fraction as a {@code BigDecimal}.
700     * @throws ArithmeticException if {@code roundingMode} == {@link RoundingMode#UNNECESSARY} and
701     *      the specified scale is insufficient to represent the result of the division exactly.
702     * @see BigDecimal
703     */
704    public BigDecimal bigDecimalValue(final int scale, RoundingMode roundingMode) {
705        return new BigDecimal(numerator).divide(new BigDecimal(denominator), scale, roundingMode);
706    }
707
708    /**
709     * Adds the specified {@code value} to this fraction, returning
710     * the result in reduced form.
711     *
712     * @param value Value to add.
713     * @return {@code this + value}.
714     */
715    public BigFraction add(final int value) {
716        return add(BigInteger.valueOf(value));
717    }
718
719    /**
720     * Adds the specified {@code value} to this fraction, returning
721     * the result in reduced form.
722     *
723     * @param value Value to add.
724     * @return {@code this + value}.
725     */
726    public BigFraction add(final long value) {
727        return add(BigInteger.valueOf(value));
728    }
729
730    /**
731     * Adds the specified {@code value} to this fraction, returning
732     * the result in reduced form.
733     *
734     * @param value Value to add.
735     * @return {@code this + value}.
736     */
737    public BigFraction add(final BigInteger value) {
738        if (value.signum() == 0) {
739            return this;
740        }
741        if (isZero()) {
742            return of(value);
743        }
744
745        return of(numerator.add(denominator.multiply(value)), denominator);
746    }
747
748    /**
749     * Adds the specified {@code value} to this fraction, returning
750     * the result in reduced form.
751     *
752     * @param value Value to add.
753     * @return {@code this + value}.
754     */
755    @Override
756    public BigFraction add(final BigFraction value) {
757        if (value.isZero()) {
758            return this;
759        }
760        if (isZero()) {
761            return value;
762        }
763
764        final BigInteger num;
765        final BigInteger den;
766
767        if (denominator.equals(value.denominator)) {
768            num = numerator.add(value.numerator);
769            den = denominator;
770        } else {
771            num = (numerator.multiply(value.denominator)).add((value.numerator).multiply(denominator));
772            den = denominator.multiply(value.denominator);
773        }
774
775        if (num.signum() == 0) {
776            return ZERO;
777        }
778
779        return new BigFraction(num, den);
780    }
781
782    /**
783     * Subtracts the specified {@code value} from this fraction, returning
784     * the result in reduced form.
785     *
786     * @param value Value to subtract.
787     * @return {@code this - value}.
788     */
789    public BigFraction subtract(final int value) {
790        return subtract(BigInteger.valueOf(value));
791    }
792
793    /**
794     * Subtracts the specified {@code value} from this fraction, returning
795     * the result in reduced form.
796     *
797     * @param value Value to subtract.
798     * @return {@code this - value}.
799     */
800    public BigFraction subtract(final long value) {
801        return subtract(BigInteger.valueOf(value));
802    }
803
804    /**
805     * Subtracts the specified {@code value} from this fraction, returning
806     * the result in reduced form.
807     *
808     * @param value Value to subtract.
809     * @return {@code this - value}.
810     */
811    public BigFraction subtract(final BigInteger value) {
812        if (value.signum() == 0) {
813            return this;
814        }
815        if (isZero()) {
816            return of(value.negate());
817        }
818
819        return of(numerator.subtract(denominator.multiply(value)), denominator);
820    }
821
822    /**
823     * Subtracts the specified {@code value} from this fraction, returning
824     * the result in reduced form.
825     *
826     * @param value Value to subtract.
827     * @return {@code this - value}.
828     */
829    @Override
830    public BigFraction subtract(final BigFraction value) {
831        if (value.isZero()) {
832            return this;
833        }
834        if (isZero()) {
835            return value.negate();
836        }
837
838        final BigInteger num;
839        final BigInteger den;
840        if (denominator.equals(value.denominator)) {
841            num = numerator.subtract(value.numerator);
842            den = denominator;
843        } else {
844            num = (numerator.multiply(value.denominator)).subtract((value.numerator).multiply(denominator));
845            den = denominator.multiply(value.denominator);
846        }
847
848        if (num.signum() == 0) {
849            return ZERO;
850        }
851
852        return new BigFraction(num, den);
853    }
854
855    /**
856     * Multiply this fraction by the passed {@code value}, returning
857     * the result in reduced form.
858     *
859     * @param value Value to multiply by.
860     * @return {@code this * value}.
861     */
862    @Override
863    public BigFraction multiply(final int value) {
864        if (value == 0 || isZero()) {
865            return ZERO;
866        }
867
868        return multiply(BigInteger.valueOf(value));
869    }
870
871    /**
872     * Multiply this fraction by the passed {@code value}, returning
873     * the result in reduced form.
874     *
875     * @param value Value to multiply by.
876     * @return {@code this * value}.
877     */
878    public BigFraction multiply(final long value) {
879        if (value == 0 || isZero()) {
880            return ZERO;
881        }
882
883        return multiply(BigInteger.valueOf(value));
884    }
885
886    /**
887     * Multiply this fraction by the passed {@code value}, returning
888     * the result in reduced form.
889     *
890     * @param value Value to multiply by.
891     * @return {@code this * value}.
892     */
893    public BigFraction multiply(final BigInteger value) {
894        if (value.signum() == 0 || isZero()) {
895            return ZERO;
896        }
897        return new BigFraction(value.multiply(numerator), denominator);
898    }
899
900    /**
901     * Multiply this fraction by the passed {@code value}, returning
902     * the result in reduced form.
903     *
904     * @param value Value to multiply by.
905     * @return {@code this * value}.
906     */
907    @Override
908    public BigFraction multiply(final BigFraction value) {
909        if (value.isZero() || isZero()) {
910            return ZERO;
911        }
912        return new BigFraction(numerator.multiply(value.numerator),
913                               denominator.multiply(value.denominator));
914    }
915
916    /**
917     * Divide this fraction by the passed {@code value}, returning
918     * the result in reduced form.
919     *
920     * @param value Value to divide by
921     * @return {@code this / value}.
922     * @throws ArithmeticException if the value to divide by is zero
923     */
924    public BigFraction divide(final int value) {
925        return divide(BigInteger.valueOf(value));
926    }
927
928    /**
929     * Divide this fraction by the passed {@code value}, returning
930     * the result in reduced form.
931     *
932     * @param value Value to divide by
933     * @return {@code this / value}.
934     * @throws ArithmeticException if the value to divide by is zero
935     */
936    public BigFraction divide(final long value) {
937        return divide(BigInteger.valueOf(value));
938    }
939
940    /**
941     * Divide this fraction by the passed {@code value}, returning
942     * the result in reduced form.
943     *
944     * @param value Value to divide by
945     * @return {@code this / value}.
946     * @throws ArithmeticException if the value to divide by is zero
947     */
948    public BigFraction divide(final BigInteger value) {
949        if (value.signum() == 0) {
950            throw new FractionException(FractionException.ERROR_DIVIDE_BY_ZERO);
951        }
952        if (isZero()) {
953            return ZERO;
954        }
955        return new BigFraction(numerator, denominator.multiply(value));
956    }
957
958    /**
959     * Divide this fraction by the passed {@code value}, returning
960     * the result in reduced form.
961     *
962     * @param value Value to divide by
963     * @return {@code this / value}.
964     * @throws ArithmeticException if the value to divide by is zero
965     */
966    @Override
967    public BigFraction divide(final BigFraction value) {
968        if (value.isZero()) {
969            throw new FractionException(FractionException.ERROR_DIVIDE_BY_ZERO);
970        }
971        if (isZero()) {
972            return ZERO;
973        }
974        // Multiply by reciprocal
975        return new BigFraction(numerator.multiply(value.denominator),
976                               denominator.multiply(value.numerator));
977    }
978
979    /**
980     * Returns a {@code BigFraction} whose value is
981     * <code>this<sup>exponent</sup></code>, returning the result in reduced form.
982     *
983     * @param exponent exponent to which this {@code BigFraction} is to be raised.
984     * @return <code>this<sup>exponent</sup></code>.
985     * @throws ArithmeticException if the intermediate result would overflow.
986     */
987    @Override
988    public BigFraction pow(final int exponent) {
989        if (exponent == 1) {
990            return this;
991        }
992        if (exponent == 0) {
993            return ONE;
994        }
995        if (isZero()) {
996            if (exponent < 0) {
997                throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
998            }
999            return ZERO;
1000        }
1001        if (exponent > 0) {
1002            return new BigFraction(numerator.pow(exponent),
1003                                   denominator.pow(exponent));
1004        }
1005        if (exponent == -1) {
1006            return this.reciprocal();
1007        }
1008        if (exponent == Integer.MIN_VALUE) {
1009            // MIN_VALUE can't be negated
1010            return new BigFraction(denominator.pow(Integer.MAX_VALUE).multiply(denominator),
1011                                   numerator.pow(Integer.MAX_VALUE).multiply(numerator));
1012        }
1013        // Note: Raise the BigIntegers to the power and then reduce.
1014        // The supported range for BigInteger is currently
1015        // +/-2^(Integer.MAX_VALUE) exclusive thus larger
1016        // exponents (long, BigInteger) are currently not supported.
1017        return new BigFraction(denominator.pow(-exponent),
1018                               numerator.pow(-exponent));
1019    }
1020
1021    /**
1022     * Returns the {@code String} representing this fraction.
1023     * Uses:
1024     * <ul>
1025     *  <li>{@code "0"} if {@code numerator} is zero.</li>
1026     *  <li>{@code "numerator"} if {@code denominator} is one.</li>
1027     *  <li>{@code "numerator / denominator"} for all other cases.</li>
1028     * </ul>
1029     *
1030     * @return a string representation of the fraction.
1031     */
1032    @Override
1033    public String toString() {
1034        final String str;
1035        if (isZero()) {
1036            str = "0";
1037        } else if (BigInteger.ONE.equals(denominator)) {
1038            str = numerator.toString();
1039        } else {
1040            str = numerator + " / " + denominator;
1041        }
1042        return str;
1043    }
1044
1045    /**
1046     * Compares this object with the specified object for order using the signed magnitude.
1047     *
1048     * @param other {@inheritDoc}
1049     * @return {@inheritDoc}
1050     */
1051    @Override
1052    public int compareTo(final BigFraction other) {
1053        final int lhsSigNum = signum();
1054        final int rhsSigNum = other.signum();
1055
1056        if (lhsSigNum != rhsSigNum) {
1057            return (lhsSigNum > rhsSigNum) ? 1 : -1;
1058        }
1059        // Same sign.
1060        // Avoid a multiply if both fractions are zero
1061        if (lhsSigNum == 0) {
1062            return 0;
1063        }
1064        // Compare absolute magnitude
1065        final BigInteger nOd = numerator.abs().multiply(other.denominator.abs());
1066        final BigInteger dOn = denominator.abs().multiply(other.numerator.abs());
1067        return lhsSigNum > 0 ?
1068            nOd.compareTo(dOn) :
1069            dOn.compareTo(nOd);
1070    }
1071
1072    /**
1073     * Test for equality with another object. If the other object is a {@code Fraction} then a
1074     * comparison is made of the sign and magnitude; otherwise {@code false} is returned.
1075     *
1076     * @param other {@inheritDoc}
1077     * @return {@inheritDoc}
1078     */
1079    @Override
1080    public boolean equals(final Object other) {
1081        if (this == other) {
1082            return true;
1083        }
1084
1085        if (other instanceof BigFraction) {
1086            // Since fractions are always in lowest terms, numerators and
1087            // denominators can be compared directly for equality.
1088            final BigFraction rhs = (BigFraction) other;
1089            if (signum() == rhs.signum()) {
1090                return numerator.abs().equals(rhs.numerator.abs()) &&
1091                       denominator.abs().equals(rhs.denominator.abs());
1092            }
1093        }
1094
1095        return false;
1096    }
1097
1098    @Override
1099    public int hashCode() {
1100        // Incorporate the sign and absolute values of the numerator and denominator.
1101        // Equivalent to:
1102        // int hash = 1;
1103        // hash = 31 * hash + numerator.abs().hashCode();
1104        // hash = 31 * hash + denominator.abs().hashCode();
1105        // hash = hash * signum()
1106        // Note: BigInteger.hashCode() * BigInteger.signum() == BigInteger.abs().hashCode().
1107        final int numS = numerator.signum();
1108        final int denS = denominator.signum();
1109        return (31 * (31 + numerator.hashCode() * numS) + denominator.hashCode() * denS) * numS * denS;
1110    }
1111
1112    /**
1113     * Calculates the sign bit, the biased exponent and the significand for a
1114     * binary floating-point representation of this {@code BigFraction}
1115     * according to the IEEE 754 standard, and encodes these values into a {@code long}
1116     * variable. The representative bits are arranged adjacent to each other and
1117     * placed at the low-order end of the returned {@code long} value, with the
1118     * least significant bits used for the significand, the next more
1119     * significant bits for the exponent, and next more significant bit for the
1120     * sign.
1121     *
1122     * <p>Warning: The arguments are not validated.
1123     *
1124     * @param exponentLength the number of bits allowed for the exponent; must be
1125     *                       between 1 and 32 (inclusive), and must not be greater
1126     *                       than {@code 63 - significandLength}
1127     * @param significandLength the number of bits allowed for the significand
1128     *                          (excluding the implicit leading 1-bit in
1129     *                          normalized numbers, e.g. 52 for a double-precision
1130     *                          floating-point number); must be between 1 and
1131     *                          {@code 63 - exponentLength} (inclusive)
1132     * @return the bits of an IEEE 754 binary floating-point representation of
1133     * this fraction encoded in a {@code long}, as described above.
1134     */
1135    private long toFloatingPointBits(int exponentLength, int significandLength) {
1136        // Assume the following conditions:
1137        //assert exponentLength >= 1;
1138        //assert exponentLength <= 32;
1139        //assert significandLength >= 1;
1140        //assert significandLength <= 63 - exponentLength;
1141
1142        if (isZero()) {
1143            return 0L;
1144        }
1145
1146        final long sign = (numerator.signum() * denominator.signum()) == -1 ? 1L : 0L;
1147        final BigInteger positiveNumerator = numerator.abs();
1148        final BigInteger positiveDenominator = denominator.abs();
1149
1150        /*
1151         * The most significant 1-bit of a non-zero number is not explicitly
1152         * stored in the significand of an IEEE 754 normalized binary
1153         * floating-point number, so we need to round the value of this fraction
1154         * to (significandLength + 1) bits. In order to do this, we calculate
1155         * the most significant (significandLength + 2) bits, and then, based on
1156         * the least significant of those bits, find out whether we need to
1157         * round up or down.
1158         *
1159         * First, we'll remove all powers of 2 from the denominator because they
1160         * are not relevant for the significand of the prospective binary
1161         * floating-point value.
1162         */
1163        final int denRightShift = positiveDenominator.getLowestSetBit();
1164        final BigInteger divisor = positiveDenominator.shiftRight(denRightShift);
1165
1166        /*
1167         * Now, we're going to calculate the (significandLength + 2) most
1168         * significant bits of the fraction's value using integer division. To
1169         * guarantee that the quotient of the division has at least
1170         * (significandLength + 2) bits, the bit length of the dividend must
1171         * exceed that of the divisor by at least that amount.
1172         *
1173         * If the denominator has prime factors other than 2, i.e. if the
1174         * divisor was not reduced to 1, an excess of exactly
1175         * (significandLength + 2) bits is sufficient, because the knowledge
1176         * that the fractional part of the precise quotient's binary
1177         * representation does not terminate is enough information to resolve
1178         * cases where the most significant (significandLength + 2) bits alone
1179         * are not conclusive.
1180         *
1181         * Otherwise, the quotient must be calculated exactly and the bit length
1182         * of the numerator can only be reduced as long as no precision is lost
1183         * in the process (meaning it can have powers of 2 removed, like the
1184         * denominator).
1185         */
1186        int numRightShift = positiveNumerator.bitLength() - divisor.bitLength() - (significandLength + 2);
1187        if (numRightShift > 0 &&
1188            divisor.equals(BigInteger.ONE)) {
1189            numRightShift = Math.min(numRightShift, positiveNumerator.getLowestSetBit());
1190        }
1191        final BigInteger dividend = positiveNumerator.shiftRight(numRightShift);
1192
1193        final BigInteger quotient = dividend.divide(divisor);
1194
1195        int quotRightShift = quotient.bitLength() - (significandLength + 1);
1196        long significand = roundAndRightShift(
1197                quotient,
1198                quotRightShift,
1199                !divisor.equals(BigInteger.ONE)
1200        ).longValue();
1201
1202        /*
1203         * If the significand had to be rounded up, this could have caused the
1204         * bit length of the significand to increase by one.
1205         */
1206        if ((significand & (1L << (significandLength + 1))) != 0) {
1207            significand >>= 1;
1208            quotRightShift++;
1209        }
1210
1211        /*
1212         * Now comes the exponent. The absolute value of this fraction based on
1213         * the current local variables is:
1214         *
1215         * significand * 2^(numRightShift - denRightShift + quotRightShift)
1216         *
1217         * To get the unbiased exponent for the floating-point value, we need to
1218         * add (significandLength) to the above exponent, because all but the
1219         * most significant bit of the significand will be treated as a
1220         * fractional part. To convert the unbiased exponent to a biased
1221         * exponent, we also need to add the exponent bias.
1222         */
1223        final int exponentBias = (1 << (exponentLength - 1)) - 1;
1224        long exponent = (long) numRightShift - denRightShift + quotRightShift + significandLength + exponentBias;
1225        final long maxExponent = (1L << exponentLength) - 1L; //special exponent for infinities and NaN
1226
1227        if (exponent >= maxExponent) { //infinity
1228            exponent = maxExponent;
1229            significand = 0L;
1230        } else if (exponent > 0) { //normalized number
1231            significand &= -1L >>> (64 - significandLength); //remove implicit leading 1-bit
1232        } else { //smaller than the smallest normalized number
1233            /*
1234             * We need to round the quotient to fewer than
1235             * (significandLength + 1) bits. This must be done with the original
1236             * quotient and not with the current significand, because the loss
1237             * of precision in the previous rounding might cause a rounding of
1238             * the current significand's value to produce a different result
1239             * than a rounding of the original quotient.
1240             *
1241             * So we find out how many high-order bits from the quotient we can
1242             * transfer into the significand. The absolute value of the fraction
1243             * is:
1244             *
1245             * quotient * 2^(numRightShift - denRightShift)
1246             *
1247             * To get the significand, we need to right shift the quotient so
1248             * that the above exponent becomes (1 - exponentBias - significandLength)
1249             * (the unbiased exponent of a subnormal floating-point number is
1250             * defined as equivalent to the minimum unbiased exponent of a
1251             * normalized floating-point number, and (- significandLength)
1252             * because the significand will be treated as the fractional part).
1253             */
1254            significand = roundAndRightShift(quotient,
1255                                             (1 - exponentBias - significandLength) - (numRightShift - denRightShift),
1256                                             !divisor.equals(BigInteger.ONE)).longValue();
1257            exponent = 0L;
1258
1259            /*
1260             * Note: It is possible that an otherwise subnormal number will
1261             * round up to the smallest normal number. However, this special
1262             * case does not need to be treated separately, because the
1263             * overflowing highest-order bit of the significand will then simply
1264             * become the lowest-order bit of the exponent, increasing the
1265             * exponent from 0 to 1 and thus establishing the implicity of the
1266             * leading 1-bit.
1267             */
1268        }
1269
1270        return (sign << (significandLength + exponentLength)) |
1271            (exponent << significandLength) |
1272            significand;
1273    }
1274
1275    /**
1276     * Rounds an integer to the specified power of two (i.e. the minimum number of
1277     * low-order bits that must be zero) and performs a right-shift by this
1278     * amount. The rounding mode applied is round to nearest, with ties rounding
1279     * to even (meaning the prospective least significant bit must be zero). The
1280     * number can optionally be treated as though it contained at
1281     * least one 0-bit and one 1-bit in its fractional part, to influence the result in cases
1282     * that would otherwise be a tie.
1283     * @param value the number to round and right-shift
1284     * @param bits the power of two to which to round; must be positive
1285     * @param hasFractionalBits whether the number should be treated as though
1286     *                          it contained a non-zero fractional part
1287     * @return a {@code BigInteger} as described above
1288     */
1289    private static BigInteger roundAndRightShift(BigInteger value, int bits, boolean hasFractionalBits) {
1290        // Assumptions:
1291        // assert bits > 0
1292
1293        BigInteger result = value.shiftRight(bits);
1294        if (value.testBit(bits - 1) &&
1295            (hasFractionalBits ||
1296             value.getLowestSetBit() < bits - 1 ||
1297             value.testBit(bits))) {
1298            result = result.add(BigInteger.ONE); //round up
1299        }
1300
1301        return result;
1302    }
1303}