Class LongMath


  • @GwtCompatible
    public final class LongMath
    extends java.lang.Object
    A class for arithmetic on values of type long. Where possible, methods are defined and named analogously to their BigInteger counterparts.

    The implementations of many methods in this class are based on material from Henry S. Warren, Jr.'s Hacker's Delight, (Addison Wesley, 2002).

    Similar functionality for int and for BigInteger can be found in IntMath and BigIntegerMath respectively. For other common operations on long values, see Longs.

    Since:
    11.0
    Author:
    Louis Wasserman
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static long binomial​(int n, int k)
      Returns n choose k, also known as the binomial coefficient of n and k, or Long.MAX_VALUE if the result does not fit in a long.
      static long ceilingPowerOfTwo​(long x)
      Returns the smallest power of two greater than or equal to x.
      static long checkedAdd​(long a, long b)
      Returns the sum of a and b, provided it does not overflow.
      static long checkedMultiply​(long a, long b)
      Returns the product of a and b, provided it does not overflow.
      static long checkedPow​(long b, int k)
      Returns the b to the kth power, provided it does not overflow.
      static long checkedSubtract​(long a, long b)
      Returns the difference of a and b, provided it does not overflow.
      static long divide​(long p, long q, java.math.RoundingMode mode)
      Returns the result of dividing p by q, rounding using the specified RoundingMode.
      static long factorial​(int n)
      Returns n!, that is, the product of the first n positive integers, 1 if n == 0, or Long.MAX_VALUE if the result does not fit in a long.
      static long floorPowerOfTwo​(long x)
      Returns the largest power of two less than or equal to x.
      static long gcd​(long a, long b)
      Returns the greatest common divisor of a, b.
      static boolean isPowerOfTwo​(long x)
      Returns true if x represents a power of two.
      static boolean isPrime​(long n)
      Returns true if n is a prime number: an integer greater than one that cannot be factored into a product of smaller positive integers.
      static int log10​(long x, java.math.RoundingMode mode)
      Returns the base-10 logarithm of x, rounded according to the specified rounding mode.
      static int log2​(long x, java.math.RoundingMode mode)
      Returns the base-2 logarithm of x, rounded according to the specified rounding mode.
      static long mean​(long x, long y)
      Returns the arithmetic mean of x and y, rounded toward negative infinity.
      static int mod​(long x, int m)
      Returns x mod m, a non-negative value less than m.
      static long mod​(long x, long m)
      Returns x mod m, a non-negative value less than m.
      static long pow​(long b, int k)
      Returns b to the kth power.
      static double roundToDouble​(long x, java.math.RoundingMode mode)
      Returns x, rounded to a double with the specified rounding mode.
      static long saturatedAbs​(long x)
      Returns the closest representable long to the absolute value of x.
      static long saturatedAdd​(long a, long b)
      Returns the sum of a and b unless it would overflow or underflow in which case Long.MAX_VALUE or Long.MIN_VALUE is returned, respectively.
      static long saturatedMultiply​(long a, long b)
      Returns the product of a and b unless it would overflow or underflow in which case Long.MAX_VALUE or Long.MIN_VALUE is returned, respectively.
      static long saturatedPow​(long b, int k)
      Returns the b to the kth power, unless it would overflow or underflow in which case Long.MAX_VALUE or Long.MIN_VALUE is returned, respectively.
      static long saturatedSubtract​(long a, long b)
      Returns the difference of a and b unless it would overflow or underflow in which case Long.MAX_VALUE or Long.MIN_VALUE is returned, respectively.
      static long sqrt​(long x, java.math.RoundingMode mode)
      Returns the square root of x, rounded with the specified rounding mode.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • ceilingPowerOfTwo

        public static long ceilingPowerOfTwo​(long x)
        Returns the smallest power of two greater than or equal to x. This is equivalent to checkedPow(2, log2(x, CEILING)).
        Throws:
        java.lang.IllegalArgumentException - if x <= 0
        java.lang.ArithmeticException - of the next-higher power of two is not representable as a long, i.e. when x > 2^62
        Since:
        20.0
      • floorPowerOfTwo

        public static long floorPowerOfTwo​(long x)
        Returns the largest power of two less than or equal to x. This is equivalent to checkedPow(2, log2(x, FLOOR)).
        Throws:
        java.lang.IllegalArgumentException - if x <= 0
        Since:
        20.0
      • isPowerOfTwo

        public static boolean isPowerOfTwo​(long x)
        Returns true if x represents a power of two.

        This differs from Long.bitCount(x) == 1, because Long.bitCount(Long.MIN_VALUE) == 1, but Long.MIN_VALUE is not a power of two.

      • log2

        public static int log2​(long x,
                               java.math.RoundingMode mode)
        Returns the base-2 logarithm of x, rounded according to the specified rounding mode.
        Throws:
        java.lang.IllegalArgumentException - if x <= 0
        java.lang.ArithmeticException - if mode is RoundingMode.UNNECESSARY and x is not a power of two
      • log10

        @GwtIncompatible
        public static int log10​(long x,
                                java.math.RoundingMode mode)
        Returns the base-10 logarithm of x, rounded according to the specified rounding mode.
        Throws:
        java.lang.IllegalArgumentException - if x <= 0
        java.lang.ArithmeticException - if mode is RoundingMode.UNNECESSARY and x is not a power of ten
      • pow

        @GwtIncompatible
        public static long pow​(long b,
                               int k)
        Returns b to the kth power. Even if the result overflows, it will be equal to BigInteger.valueOf(b).pow(k).longValue(). This implementation runs in O(log k) time.
        Throws:
        java.lang.IllegalArgumentException - if k < 0
      • sqrt

        @GwtIncompatible
        public static long sqrt​(long x,
                                java.math.RoundingMode mode)
        Returns the square root of x, rounded with the specified rounding mode.
        Throws:
        java.lang.IllegalArgumentException - if x < 0
        java.lang.ArithmeticException - if mode is RoundingMode.UNNECESSARY and sqrt(x) is not an integer
      • divide

        @GwtIncompatible
        public static long divide​(long p,
                                  long q,
                                  java.math.RoundingMode mode)
        Returns the result of dividing p by q, rounding using the specified RoundingMode. If the RoundingMode is RoundingMode.DOWN, then this method is equivalent to regular Java division, p / q; and if it is RoundingMode.FLOOR, then this method is equivalent to Math.floorDiv(p, q).
        Throws:
        java.lang.ArithmeticException - if q == 0, or if mode == UNNECESSARY and a is not an integer multiple of b
      • mod

        @GwtIncompatible
        public static int mod​(long x,
                              int m)
        Returns x mod m, a non-negative value less than m. This differs from x % m, which might be negative.

        For example:

        Throws:
        java.lang.ArithmeticException - if m <= 0
        See Also:
        Remainder Operator
      • mod

        @GwtIncompatible
        public static long mod​(long x,
                               long m)
        Returns x mod m, a non-negative value less than m. This differs from x % m, which might be negative.

        For example:

        Throws:
        java.lang.ArithmeticException - if m <= 0
        See Also:
        Remainder Operator
      • gcd

        public static long gcd​(long a,
                               long b)
        Returns the greatest common divisor of a, b. Returns 0 if a == 0 && b == 0.
        Throws:
        java.lang.IllegalArgumentException - if a < 0 or b < 0
      • checkedAdd

        @InlineMe(replacement="Math.addExact(a, b)")
        public static long checkedAdd​(long a,
                                      long b)
        Returns the sum of a and b, provided it does not overflow.

        Note: this method is now unnecessary and should be treated as deprecated; use Math.addExact(long, long) instead. Note that if both arguments are int values, writing Math.addExact(a, b) will call the Math.addExact(int, int) overload, not Math.addExact(long, long). Also note that adding two int values can never overflow a long, so you can just write (long) a + b.

        Throws:
        java.lang.ArithmeticException - if a + b overflows in signed long arithmetic
      • checkedSubtract

        @InlineMe(replacement="Math.subtractExact(a, b)")
        public static long checkedSubtract​(long a,
                                           long b)
        Returns the difference of a and b, provided it does not overflow.

        Note: this method is now unnecessary and should be treated as deprecated; use Math.subtractExact(long, long) instead. Note that if both arguments are int values, writing Math.subtractExact(a, b) will call the Math.subtractExact(int, int) overload, not Math.subtractExact(long, long). Also note that subtracting two int values can never overflow a long, so you can just write (long) a - b.

        Throws:
        java.lang.ArithmeticException - if a - b overflows in signed long arithmetic
      • checkedMultiply

        @InlineMe(replacement="Math.multiplyExact(a, b)")
        public static long checkedMultiply​(long a,
                                           long b)
        Returns the product of a and b, provided it does not overflow.

        Note: this method is now unnecessary and should be treated as deprecated; use Math.multiplyExact(long, long) instead. Note that if both arguments are int values, writing Math.multiplyExact(a, b) will call the Math.multiplyExact(int, int) overload, not Math.multiplyExact(long, long). Also note that multiplying two int values can never overflow a long, so you can just write (long) a * b.

        Throws:
        java.lang.ArithmeticException - if a * b overflows in signed long arithmetic
      • checkedPow

        @GwtIncompatible
        public static long checkedPow​(long b,
                                      int k)
        Returns the b to the kth power, provided it does not overflow.
        Throws:
        java.lang.ArithmeticException - if b to the kth power overflows in signed long arithmetic
      • saturatedAdd

        public static long saturatedAdd​(long a,
                                        long b)
        Returns the sum of a and b unless it would overflow or underflow in which case Long.MAX_VALUE or Long.MIN_VALUE is returned, respectively.
        Since:
        20.0
      • saturatedSubtract

        public static long saturatedSubtract​(long a,
                                             long b)
        Returns the difference of a and b unless it would overflow or underflow in which case Long.MAX_VALUE or Long.MIN_VALUE is returned, respectively.
        Since:
        20.0
      • saturatedMultiply

        public static long saturatedMultiply​(long a,
                                             long b)
        Returns the product of a and b unless it would overflow or underflow in which case Long.MAX_VALUE or Long.MIN_VALUE is returned, respectively.
        Since:
        20.0
      • saturatedPow

        public static long saturatedPow​(long b,
                                        int k)
        Returns the b to the kth power, unless it would overflow or underflow in which case Long.MAX_VALUE or Long.MIN_VALUE is returned, respectively.
        Since:
        20.0
      • factorial

        @GwtIncompatible
        public static long factorial​(int n)
        Returns n!, that is, the product of the first n positive integers, 1 if n == 0, or Long.MAX_VALUE if the result does not fit in a long.
        Throws:
        java.lang.IllegalArgumentException - if n < 0
      • binomial

        public static long binomial​(int n,
                                    int k)
        Returns n choose k, also known as the binomial coefficient of n and k, or Long.MAX_VALUE if the result does not fit in a long.
        Throws:
        java.lang.IllegalArgumentException - if n < 0, k < 0, or k > n
      • mean

        public static long mean​(long x,
                                long y)
        Returns the arithmetic mean of x and y, rounded toward negative infinity. This method is resilient to overflow.
        Since:
        14.0
      • isPrime

        @GwtIncompatible
        public static boolean isPrime​(long n)
        Returns true if n is a prime number: an integer greater than one that cannot be factored into a product of smaller positive integers. Returns false if n is zero, one, or a composite number (one which can be factored into smaller positive integers).

        To test larger numbers, use BigInteger.isProbablePrime(int).

        Throws:
        java.lang.IllegalArgumentException - if n is negative
        Since:
        20.0
      • roundToDouble

        @GwtIncompatible
        public static double roundToDouble​(long x,
                                           java.math.RoundingMode mode)
        Returns x, rounded to a double with the specified rounding mode. If x is precisely representable as a double, its double value will be returned; otherwise, the rounding will choose between the two nearest representable values with mode.

        For the case of RoundingMode.HALF_EVEN, this implementation uses the IEEE 754 default rounding mode: if the two nearest representable values are equally near, the one with the least significant bit zero is chosen. (In such cases, both of the nearest representable values are even integers; this method returns the one that is a multiple of a greater power of two.)

        Throws:
        java.lang.ArithmeticException - if mode is RoundingMode.UNNECESSARY and x is not precisely representable as a double
        Since:
        30.0
      • saturatedAbs

        public static long saturatedAbs​(long x)
        Returns the closest representable long to the absolute value of x.

        This is the same thing as the true absolute value of x except in the case when x is Long.MIN_VALUE, in which case this returns Long.MAX_VALUE. (Note that Long.MAX_VALUE is mathematically equal to -Long.MIN_VALUE - 1.)

        There are three common APIs for determining the absolute value of a long, all of which behave identically except when passed Long.MIN_VALUE. Those methods are:

        • Math.abs(long), which returns Long.MIN_VALUE when passed Long.MIN_VALUE
        • Math#absExact(long), which throws ArithmeticException when passed Long.MIN_VALUE
        • this method, LongMath.saturatedAbs(long), which returns Long.MAX_VALUE when passed Long.MIN_VALUE

        Note that if your only goal is to turn a well-distributed long (such as a random number) into a well-distributed nonnegative number, the most even distribution is achieved not by this method or other absolute value methods, but by x & Long.MAX_VALUE.

        Since:
        33.5.0