ArithmeticUtils.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      https://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */
  21. package org.hipparchus.util;

  22. import java.math.BigInteger;

  23. import org.hipparchus.exception.Localizable;
  24. import org.hipparchus.exception.LocalizedCoreFormats;
  25. import org.hipparchus.exception.MathRuntimeException;
  26. import org.hipparchus.exception.MathIllegalArgumentException;

  27. /**
  28.  * Some useful, arithmetics related, additions to the built-in functions in
  29.  * {@link Math}.
  30.  */
  31. public final class ArithmeticUtils {

  32.     /** Private constructor. */
  33.     private ArithmeticUtils() {
  34.         super();
  35.     }

  36.     /**
  37.      * Add two integers, checking for overflow.
  38.      *
  39.      * @param x an addend
  40.      * @param y an addend
  41.      * @return the sum {@code x+y}
  42.      * @throws MathRuntimeException if the result can not be represented
  43.      * as an {@code int}.
  44.      */
  45.     public static int addAndCheck(int x, int y)
  46.             throws MathRuntimeException {
  47.         long s = (long) x + (long) y; // NOPMD - casts are intentional here
  48.         if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
  49.             throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_ADDITION, x, y);
  50.         }
  51.         return (int)s;
  52.     }

  53.     /**
  54.      * Add two long integers, checking for overflow.
  55.      *
  56.      * @param a an addend
  57.      * @param b an addend
  58.      * @return the sum {@code a+b}
  59.      * @throws MathRuntimeException if the result can not be represented as an long
  60.      */
  61.     public static long addAndCheck(long a, long b) throws MathRuntimeException {
  62.         return addAndCheck(a, b, LocalizedCoreFormats.OVERFLOW_IN_ADDITION);
  63.     }

  64.     /**
  65.      * Computes the greatest common divisor of the absolute value of two
  66.      * numbers, using a modified version of the "binary gcd" method.
  67.      * See Knuth 4.5.2 algorithm B.
  68.      * The algorithm is due to Josef Stein (1961).
  69.      * <br>
  70.      * Special cases:
  71.      * <ul>
  72.      *  <li>The invocations
  73.      *   {@code gcd(Integer.MIN_VALUE, Integer.MIN_VALUE)},
  74.      *   {@code gcd(Integer.MIN_VALUE, 0)} and
  75.      *   {@code gcd(0, Integer.MIN_VALUE)} throw an
  76.      *   {@code ArithmeticException}, because the result would be 2^31, which
  77.      *   is too large for an int value.</li>
  78.      *  <li>The result of {@code gcd(x, x)}, {@code gcd(0, x)} and
  79.      *   {@code gcd(x, 0)} is the absolute value of {@code x}, except
  80.      *   for the special cases above.</li>
  81.      *  <li>The invocation {@code gcd(0, 0)} is the only one which returns
  82.      *   {@code 0}.</li>
  83.      * </ul>
  84.      *
  85.      * @param p Number.
  86.      * @param q Number.
  87.      * @return the greatest common divisor (never negative).
  88.      * @throws MathRuntimeException if the result cannot be represented as
  89.      * a non-negative {@code int} value.
  90.      */
  91.     public static int gcd(int p, int q) throws MathRuntimeException {
  92.         int a = p;
  93.         int b = q;
  94.         if (a == 0 ||
  95.             b == 0) {
  96.             if (a == Integer.MIN_VALUE ||
  97.                 b == Integer.MIN_VALUE) {
  98.                 throw new MathRuntimeException(LocalizedCoreFormats.GCD_OVERFLOW_32_BITS,
  99.                                                p, q);
  100.             }
  101.             return FastMath.abs(a + b);
  102.         }

  103.         long al = a;
  104.         long bl = b;
  105.         boolean useLong = false;
  106.         if (a < 0) {
  107.             if(Integer.MIN_VALUE == a) {
  108.                 useLong = true;
  109.             } else {
  110.                 a = -a;
  111.             }
  112.             al = -al;
  113.         }
  114.         if (b < 0) {
  115.             if (Integer.MIN_VALUE == b) {
  116.                 useLong = true;
  117.             } else {
  118.                 b = -b;
  119.             }
  120.             bl = -bl;
  121.         }
  122.         if (useLong) {
  123.             if(al == bl) {
  124.                 throw new MathRuntimeException(LocalizedCoreFormats.GCD_OVERFLOW_32_BITS,
  125.                                                p, q);
  126.             }
  127.             long blbu = bl;
  128.             bl = al;
  129.             al = blbu % al;
  130.             if (al == 0) {
  131.                 if (bl > Integer.MAX_VALUE) {
  132.                     throw new MathRuntimeException(LocalizedCoreFormats.GCD_OVERFLOW_32_BITS,
  133.                                                    p, q);
  134.                 }
  135.                 return (int) bl;
  136.             }
  137.             blbu = bl;

  138.             // Now "al" and "bl" fit in an "int".
  139.             b = (int) al;
  140.             a = (int) (blbu % al);
  141.         }

  142.         return gcdPositive(a, b);
  143.     }

  144.     /**
  145.      * Computes the greatest common divisor of two <em>positive</em> numbers
  146.      * (this precondition is <em>not</em> checked and the result is undefined
  147.      * if not fulfilled) using the "binary gcd" method which avoids division
  148.      * and modulo operations.
  149.      * See Knuth 4.5.2 algorithm B.
  150.      * The algorithm is due to Josef Stein (1961).
  151.      * <p>
  152.      * Special cases:
  153.      * <ul>
  154.      *  <li>The result of {@code gcd(x, x)}, {@code gcd(0, x)} and
  155.      *   {@code gcd(x, 0)} is the value of {@code x}.</li>
  156.      *  <li>The invocation {@code gcd(0, 0)} is the only one which returns
  157.      *   {@code 0}.</li>
  158.      * </ul>
  159.      *
  160.      * @param a Positive number.
  161.      * @param b Positive number.
  162.      * @return the greatest common divisor.
  163.      */
  164.     private static int gcdPositive(int a, int b) {
  165.         if (a == 0) {
  166.             return b;
  167.         }
  168.         else if (b == 0) {
  169.             return a;
  170.         }

  171.         // Make "a" and "b" odd, keeping track of common power of 2.
  172.         final int aTwos = Integer.numberOfTrailingZeros(a);
  173.         a >>= aTwos;
  174.         final int bTwos = Integer.numberOfTrailingZeros(b);
  175.         b >>= bTwos;
  176.         final int shift = FastMath.min(aTwos, bTwos);

  177.         // "a" and "b" are positive.
  178.         // If a > b then "gdc(a, b)" is equal to "gcd(a - b, b)".
  179.         // If a < b then "gcd(a, b)" is equal to "gcd(b - a, a)".
  180.         // Hence, in the successive iterations:
  181.         //  "a" becomes the absolute difference of the current values,
  182.         //  "b" becomes the minimum of the current values.
  183.         while (a != b) {
  184.             final int delta = a - b;
  185.             b = Math.min(a, b);
  186.             a = Math.abs(delta);

  187.             // Remove any power of 2 in "a" ("b" is guaranteed to be odd).
  188.             a >>= Integer.numberOfTrailingZeros(a);
  189.         }

  190.         // Recover the common power of 2.
  191.         return a << shift;
  192.     }

  193.     /**
  194.      * Gets the greatest common divisor of the absolute value of two numbers,
  195.      * using the "binary gcd" method which avoids division and modulo
  196.      * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
  197.      * Stein (1961).
  198.      * <p>
  199.      * Special cases:
  200.      * <ul>
  201.      * <li>The invocations
  202.      * {@code gcd(Long.MIN_VALUE, Long.MIN_VALUE)},
  203.      * {@code gcd(Long.MIN_VALUE, 0L)} and
  204.      * {@code gcd(0L, Long.MIN_VALUE)} throw an
  205.      * {@code ArithmeticException}, because the result would be 2^63, which
  206.      * is too large for a long value.</li>
  207.      * <li>The result of {@code gcd(x, x)}, {@code gcd(0L, x)} and
  208.      * {@code gcd(x, 0L)} is the absolute value of {@code x}, except
  209.      * for the special cases above.
  210.      * <li>The invocation {@code gcd(0L, 0L)} is the only one which returns
  211.      * {@code 0L}.</li>
  212.      * </ul>
  213.      *
  214.      * @param p Number.
  215.      * @param q Number.
  216.      * @return the greatest common divisor, never negative.
  217.      * @throws MathRuntimeException if the result cannot be represented as
  218.      * a non-negative {@code long} value.
  219.      */
  220.     public static long gcd(final long p, final long q) throws MathRuntimeException {
  221.         long u = p;
  222.         long v = q;
  223.         if ((u == 0) || (v == 0)) {
  224.             if ((u == Long.MIN_VALUE) || (v == Long.MIN_VALUE)){
  225.                 throw new MathRuntimeException(LocalizedCoreFormats.GCD_OVERFLOW_64_BITS,
  226.                                                p, q);
  227.             }
  228.             return FastMath.abs(u) + FastMath.abs(v);
  229.         }
  230.         // keep u and v negative, as negative integers range down to
  231.         // -2^63, while positive numbers can only be as large as 2^63-1
  232.         // (i.e. we can't necessarily negate a negative number without
  233.         // overflow)
  234.         /* assert u!=0 && v!=0; */
  235.         if (u > 0) {
  236.             u = -u;
  237.         } // make u negative
  238.         if (v > 0) {
  239.             v = -v;
  240.         } // make v negative
  241.         // B1. [Find power of 2]
  242.         int k = 0;
  243.         while ((u & 1) == 0 && (v & 1) == 0 && k < 63) { // while u and v are
  244.                                                             // both even...
  245.             u /= 2;
  246.             v /= 2;
  247.             k++; // cast out twos.
  248.         }
  249.         if (k == 63) {
  250.             throw new MathRuntimeException(LocalizedCoreFormats.GCD_OVERFLOW_64_BITS,
  251.                                            p, q);
  252.         }
  253.         // B2. Initialize: u and v have been divided by 2^k and at least
  254.         // one is odd.
  255.         long t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
  256.         // t negative: u was odd, v may be even (t replaces v)
  257.         // t positive: u was even, v is odd (t replaces u)
  258.         do {
  259.             /* assert u<0 && v<0; */
  260.             // B4/B3: cast out twos from t.
  261.             while ((t & 1) == 0) { // while t is even..
  262.                 t /= 2; // cast out twos
  263.             }
  264.             // B5 [reset max(u,v)]
  265.             if (t > 0) {
  266.                 u = -t;
  267.             } else {
  268.                 v = t;
  269.             }
  270.             // B6/B3. at this point both u and v should be odd.
  271.             t = (v - u) / 2;
  272.             // |u| larger: t positive (replace u)
  273.             // |v| larger: t negative (replace v)
  274.         } while (t != 0);
  275.         return -u * (1L << k); // gcd is u*2^k
  276.     }

  277.     /**
  278.      * Returns the least common multiple of the absolute value of two numbers,
  279.      * using the formula {@code lcm(a,b) = (a / gcd(a,b)) * b}.
  280.      * <p>
  281.      * Special cases:
  282.      * <ul>
  283.      * <li>The invocations {@code lcm(Integer.MIN_VALUE, n)} and
  284.      * {@code lcm(n, Integer.MIN_VALUE)}, where {@code abs(n)} is a
  285.      * power of 2, throw an {@code ArithmeticException}, because the result
  286.      * would be 2^31, which is too large for an int value.</li>
  287.      * <li>The result of {@code lcm(0, x)} and {@code lcm(x, 0)} is
  288.      * {@code 0} for any {@code x}.
  289.      * </ul>
  290.      *
  291.      * @param a Number.
  292.      * @param b Number.
  293.      * @return the least common multiple, never negative.
  294.      * @throws MathRuntimeException if the result cannot be represented as
  295.      * a non-negative {@code int} value.
  296.      */
  297.     public static int lcm(int a, int b) throws MathRuntimeException {
  298.         if (a == 0 || b == 0){
  299.             return 0;
  300.         }
  301.         int lcm = FastMath.abs(mulAndCheck(a / gcd(a, b), b));
  302.         if (lcm == Integer.MIN_VALUE) {
  303.             throw new MathRuntimeException(LocalizedCoreFormats.LCM_OVERFLOW_32_BITS, a, b);
  304.         }
  305.         return lcm;
  306.     }

  307.     /**
  308.      * Returns the least common multiple of the absolute value of two numbers,
  309.      * using the formula {@code lcm(a,b) = (a / gcd(a,b)) * b}.
  310.      * <p>
  311.      * Special cases:
  312.      * <ul>
  313.      * <li>The invocations {@code lcm(Long.MIN_VALUE, n)} and
  314.      * {@code lcm(n, Long.MIN_VALUE)}, where {@code abs(n)} is a
  315.      * power of 2, throw an {@code ArithmeticException}, because the result
  316.      * would be 2^63, which is too large for an int value.</li>
  317.      * <li>The result of {@code lcm(0L, x)} and {@code lcm(x, 0L)} is
  318.      * {@code 0L} for any {@code x}.
  319.      * </ul>
  320.      *
  321.      * @param a Number.
  322.      * @param b Number.
  323.      * @return the least common multiple, never negative.
  324.      * @throws MathRuntimeException if the result cannot be represented
  325.      * as a non-negative {@code long} value.
  326.      */
  327.     public static long lcm(long a, long b) throws MathRuntimeException {
  328.         if (a == 0 || b == 0){
  329.             return 0;
  330.         }
  331.         long lcm = FastMath.abs(mulAndCheck(a / gcd(a, b), b));
  332.         if (lcm == Long.MIN_VALUE){
  333.             throw new MathRuntimeException(LocalizedCoreFormats.LCM_OVERFLOW_64_BITS, a, b);
  334.         }
  335.         return lcm;
  336.     }

  337.     /**
  338.      * Multiply two integers, checking for overflow.
  339.      *
  340.      * @param x Factor.
  341.      * @param y Factor.
  342.      * @return the product {@code x * y}.
  343.      * @throws MathRuntimeException if the result can not be
  344.      * represented as an {@code int}.
  345.      */
  346.     public static int mulAndCheck(int x, int y) throws MathRuntimeException {
  347.         long m = ((long) x) * ((long) y);  // NOPMD - casts are intentional here
  348.         if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
  349.             throw new MathRuntimeException(LocalizedCoreFormats.ARITHMETIC_EXCEPTION);
  350.         }
  351.         return (int)m;
  352.     }

  353.     /**
  354.      * Multiply two long integers, checking for overflow.
  355.      *
  356.      * @param a Factor.
  357.      * @param b Factor.
  358.      * @return the product {@code a * b}.
  359.      * @throws MathRuntimeException if the result can not be represented
  360.      * as a {@code long}.
  361.      */
  362.     public static long mulAndCheck(long a, long b) throws MathRuntimeException {
  363.         long ret;
  364.         if (a > b) {
  365.             // use symmetry to reduce boundary cases
  366.             ret = mulAndCheck(b, a);
  367.         } else {
  368.             if (a < 0) {
  369.                 if (b < 0) {
  370.                     // check for positive overflow with negative a, negative b
  371.                     if (a >= Long.MAX_VALUE / b) {
  372.                         ret = a * b;
  373.                     } else {
  374.                         throw new MathRuntimeException(LocalizedCoreFormats.ARITHMETIC_EXCEPTION);
  375.                     }
  376.                 } else if (b > 0) {
  377.                     // check for negative overflow with negative a, positive b
  378.                     if (Long.MIN_VALUE / b <= a) {
  379.                         ret = a * b;
  380.                     } else {
  381.                         throw new MathRuntimeException(LocalizedCoreFormats.ARITHMETIC_EXCEPTION);

  382.                     }
  383.                 } else {
  384.                     // assert b == 0
  385.                     ret = 0;
  386.                 }
  387.             } else if (a > 0) {
  388.                 // assert a > 0
  389.                 // assert b > 0

  390.                 // check for positive overflow with positive a, positive b
  391.                 if (a <= Long.MAX_VALUE / b) {
  392.                     ret = a * b;
  393.                 } else {
  394.                     throw new MathRuntimeException(LocalizedCoreFormats.ARITHMETIC_EXCEPTION);
  395.                 }
  396.             } else {
  397.                 // assert a == 0
  398.                 ret = 0;
  399.             }
  400.         }
  401.         return ret;
  402.     }

  403.     /**
  404.      * Subtract two integers, checking for overflow.
  405.      *
  406.      * @param x Minuend.
  407.      * @param y Subtrahend.
  408.      * @return the difference {@code x - y}.
  409.      * @throws MathRuntimeException if the result can not be represented
  410.      * as an {@code int}.
  411.      */
  412.     public static int subAndCheck(int x, int y) throws MathRuntimeException {
  413.         long s = (long) x - (long) y; // NOPMD - casts are intentional here
  414.         if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
  415.             throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_SUBTRACTION, x, y);
  416.         }
  417.         return (int)s;
  418.     }

  419.     /**
  420.      * Subtract two long integers, checking for overflow.
  421.      *
  422.      * @param a Value.
  423.      * @param b Value.
  424.      * @return the difference {@code a - b}.
  425.      * @throws MathRuntimeException if the result can not be represented as a
  426.      * {@code long}.
  427.      */
  428.     public static long subAndCheck(long a, long b) throws MathRuntimeException {
  429.         long ret;
  430.         if (b == Long.MIN_VALUE) {
  431.             if (a < 0) {
  432.                 ret = a - b;
  433.             } else {
  434.                 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_ADDITION, a, -b);
  435.             }
  436.         } else {
  437.             // use additive inverse
  438.             ret = addAndCheck(a, -b, LocalizedCoreFormats.OVERFLOW_IN_ADDITION);
  439.         }
  440.         return ret;
  441.     }

  442.     /**
  443.      * Raise an int to an int power.
  444.      *
  445.      * @param k Number to raise.
  446.      * @param e Exponent (must be positive or zero).
  447.      * @return \( k^e \)
  448.      * @throws MathIllegalArgumentException if {@code e < 0}.
  449.      * @throws MathRuntimeException if the result would overflow.
  450.      */
  451.     public static int pow(final int k,
  452.                           final int e)
  453.         throws MathIllegalArgumentException,
  454.                MathRuntimeException {
  455.         if (e < 0) {
  456.             throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e);
  457.         }

  458.         int exp = e;
  459.         int result = 1;
  460.         int k2p    = k;
  461.         while (true) {
  462.             if ((exp & 0x1) != 0) {
  463.                 result = mulAndCheck(result, k2p);
  464.             }

  465.             exp >>= 1;
  466.         if (exp == 0) {
  467.             break;
  468.         }

  469.         k2p = mulAndCheck(k2p, k2p);
  470.         }

  471.         return result;
  472.     }

  473.     /**
  474.      * Raise a long to an int power.
  475.      *
  476.      * @param k Number to raise.
  477.      * @param e Exponent (must be positive or zero).
  478.      * @return \( k^e \)
  479.      * @throws MathIllegalArgumentException if {@code e < 0}.
  480.      * @throws MathRuntimeException if the result would overflow.
  481.      */
  482.     public static long pow(final long k,
  483.                            final int e)
  484.         throws MathIllegalArgumentException,
  485.                MathRuntimeException {
  486.         if (e < 0) {
  487.             throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e);
  488.         }

  489.         int exp = e;
  490.         long result = 1;
  491.         long k2p    = k;
  492.         while (true) {
  493.             if ((exp & 0x1) != 0) {
  494.                 result = mulAndCheck(result, k2p);
  495.             }

  496.             exp >>= 1;
  497.         if (exp == 0) {
  498.             break;
  499.         }

  500.         k2p = mulAndCheck(k2p, k2p);
  501.         }

  502.         return result;
  503.     }

  504.     /**
  505.      * Raise a BigInteger to an int power.
  506.      *
  507.      * @param k Number to raise.
  508.      * @param e Exponent (must be positive or zero).
  509.      * @return k<sup>e</sup>
  510.      * @throws MathIllegalArgumentException if {@code e < 0}.
  511.      */
  512.     public static BigInteger pow(final BigInteger k, int e) throws MathIllegalArgumentException {
  513.         if (e < 0) {
  514.             throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e);
  515.         }

  516.         return k.pow(e);
  517.     }

  518.     /**
  519.      * Raise a BigInteger to a long power.
  520.      *
  521.      * @param k Number to raise.
  522.      * @param e Exponent (must be positive or zero).
  523.      * @return k<sup>e</sup>
  524.      * @throws MathIllegalArgumentException if {@code e < 0}.
  525.      */
  526.     public static BigInteger pow(final BigInteger k, long e) throws MathIllegalArgumentException {
  527.         if (e < 0) {
  528.             throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e);
  529.         }

  530.         BigInteger result = BigInteger.ONE;
  531.         BigInteger k2p    = k;
  532.         while (e != 0) {
  533.             if ((e & 0x1) != 0) {
  534.                 result = result.multiply(k2p);
  535.             }
  536.             k2p = k2p.multiply(k2p);
  537.             e >>= 1;
  538.         }

  539.         return result;

  540.     }

  541.     /**
  542.      * Raise a BigInteger to a BigInteger power.
  543.      *
  544.      * @param k Number to raise.
  545.      * @param e Exponent (must be positive or zero).
  546.      * @return k<sup>e</sup>
  547.      * @throws MathIllegalArgumentException if {@code e < 0}.
  548.      */
  549.     public static BigInteger pow(final BigInteger k, BigInteger e) throws MathIllegalArgumentException {
  550.         if (e.compareTo(BigInteger.ZERO) < 0) {
  551.             throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e);
  552.         }

  553.         BigInteger result = BigInteger.ONE;
  554.         BigInteger k2p    = k;
  555.         while (!BigInteger.ZERO.equals(e)) {
  556.             if (e.testBit(0)) {
  557.                 result = result.multiply(k2p);
  558.             }
  559.             k2p = k2p.multiply(k2p);
  560.             e = e.shiftRight(1);
  561.         }

  562.         return result;
  563.     }

  564.     /**
  565.      * Add two long integers, checking for overflow.
  566.      *
  567.      * @param a Addend.
  568.      * @param b Addend.
  569.      * @param pattern Pattern to use for any thrown exception.
  570.      * @return the sum {@code a + b}.
  571.      * @throws MathRuntimeException if the result cannot be represented
  572.      * as a {@code long}.
  573.      */
  574.      private static long addAndCheck(long a, long b, Localizable pattern) throws MathRuntimeException {
  575.          final long result = a + b;
  576.          if (!((a ^ b) < 0 || (a ^ result) >= 0)) {
  577.              throw new MathRuntimeException(pattern, a, b);
  578.          }
  579.          return result;
  580.     }

  581.     /**
  582.      * Returns true if the argument is a power of two.
  583.      *
  584.      * @param n the number to test
  585.      * @return true if the argument is a power of two
  586.      */
  587.     public static boolean isPowerOfTwo(long n) {
  588.         return (n > 0) && ((n & (n - 1)) == 0);
  589.     }

  590.     /**
  591.      * Returns the unsigned remainder from dividing the first argument
  592.      * by the second where each argument and the result is interpreted
  593.      * as an unsigned value.
  594.      * <p>
  595.      * This method does not use the {@code long} datatype.
  596.      *
  597.      * @param dividend the value to be divided
  598.      * @param divisor the value doing the dividing
  599.      * @return the unsigned remainder of the first argument divided by
  600.      * the second argument.
  601.      */
  602.     public static int remainderUnsigned(int dividend, int divisor) {
  603.         if (divisor >= 0) {
  604.             if (dividend >= 0) {
  605.                 return dividend % divisor;
  606.             }
  607.             // The implementation is a Java port of algorithm described in the book
  608.             // "Hacker's Delight" (section "Unsigned short division from signed division").
  609.             int q = ((dividend >>> 1) / divisor) << 1;
  610.             dividend -= q * divisor;
  611.             if (dividend < 0 || dividend >= divisor) {
  612.                 dividend -= divisor;
  613.             }
  614.             return dividend;
  615.         }
  616.         return dividend >= 0 || dividend < divisor ? dividend : dividend - divisor;
  617.     }

  618.     /**
  619.      * Returns the unsigned remainder from dividing the first argument
  620.      * by the second where each argument and the result is interpreted
  621.      * as an unsigned value.
  622.      * <p>
  623.      * This method does not use the {@code BigInteger} datatype.
  624.      *
  625.      * @param dividend the value to be divided
  626.      * @param divisor the value doing the dividing
  627.      * @return the unsigned remainder of the first argument divided by
  628.      * the second argument.
  629.      */
  630.     public static long remainderUnsigned(long dividend, long divisor) {
  631.         if (divisor >= 0L) {
  632.             if (dividend >= 0L) {
  633.                 return dividend % divisor;
  634.             }
  635.             // The implementation is a Java port of algorithm described in the book
  636.             // "Hacker's Delight" (section "Unsigned short division from signed division").
  637.             long q = ((dividend >>> 1) / divisor) << 1;
  638.             dividend -= q * divisor;
  639.             if (dividend < 0L || dividend >= divisor) {
  640.                 dividend -= divisor;
  641.             }
  642.             return dividend;
  643.         }
  644.         return dividend >= 0L || dividend < divisor ? dividend : dividend - divisor;
  645.     }

  646.     /**
  647.      * Returns the unsigned quotient of dividing the first argument by
  648.      * the second where each argument and the result is interpreted as
  649.      * an unsigned value.
  650.      * <p>
  651.      * Note that in two's complement arithmetic, the three other
  652.      * basic arithmetic operations of add, subtract, and multiply are
  653.      * bit-wise identical if the two operands are regarded as both
  654.      * being signed or both being unsigned. Therefore separate {@code
  655.      * addUnsigned}, etc. methods are not provided.
  656.      * <p>
  657.      * This method does not use the {@code long} datatype.
  658.      *
  659.      * @param dividend the value to be divided
  660.      * @param divisor the value doing the dividing
  661.      * @return the unsigned quotient of the first argument divided by
  662.      * the second argument
  663.      */
  664.     public static int divideUnsigned(int dividend, int divisor) {
  665.         if (divisor >= 0) {
  666.             if (dividend >= 0) {
  667.                 return dividend / divisor;
  668.             }
  669.             // The implementation is a Java port of algorithm described in the book
  670.             // "Hacker's Delight" (section "Unsigned short division from signed division").
  671.             int q = ((dividend >>> 1) / divisor) << 1;
  672.             dividend -= q * divisor;
  673.             if (dividend < 0L || dividend >= divisor) {
  674.                 q++;
  675.             }
  676.             return q;
  677.         }
  678.         return dividend >= 0 || dividend < divisor ? 0 : 1;
  679.     }

  680.     /**
  681.      * Returns the unsigned quotient of dividing the first argument by
  682.      * the second where each argument and the result is interpreted as
  683.      * an unsigned value.
  684.      * <p>
  685.      * Note that in two's complement arithmetic, the three other
  686.      * basic arithmetic operations of add, subtract, and multiply are
  687.      * bit-wise identical if the two operands are regarded as both
  688.      * being signed or both being unsigned. Therefore separate {@code
  689.      * addUnsigned}, etc. methods are not provided.
  690.      * <p>
  691.      * This method does not use the {@code BigInteger} datatype.
  692.      *
  693.      * @param dividend the value to be divided
  694.      * @param divisor the value doing the dividing
  695.      * @return the unsigned quotient of the first argument divided by
  696.      * the second argument.
  697.      */
  698.     public static long divideUnsigned(long dividend, long divisor) {
  699.         if (divisor >= 0L) {
  700.             if (dividend >= 0L) {
  701.                 return dividend / divisor;
  702.             }
  703.             // The implementation is a Java port of algorithm described in the book
  704.             // "Hacker's Delight" (section "Unsigned short division from signed division").
  705.             long q = ((dividend >>> 1) / divisor) << 1;
  706.             dividend -= q * divisor;
  707.             if (dividend < 0L || dividend >= divisor) {
  708.                 q++;
  709.             }
  710.             return q;
  711.         }
  712.         return dividend >= 0L || dividend < divisor ? 0L : 1L;
  713.     }

  714. }