Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this article, we will see some useful Mathematical Operations available in the Guava Library.

There are four maths utility classes available with Guava:

  1. IntMath – operation on int values
  2. LongMath – operations on long values
  3. BigIntegerMath – operations on BigIntegers
  4. DoubleMath – operations on double values

2. IntMath Utility

IntMath is used to perform mathematical operations on Integer values. We’ll go through the available method list explaining each of their behavior.

2.1. binomial(int n, int k)

This function calculates the binomial coefficient of n and k. It makes sure that the result is within the integer range. Otherwise, it gives the Integer.MAX_VALUE. The answer can be derived using the formula n/k(n-k):

@Test
public void whenBinomialOnTwoInt_shouldReturnResultIfUnderInt() {
    int result = IntMath.binomial(6, 3);
 
    assertEquals(20, result);
}

@Test
public void whenBinomialOnTwoInt_shouldReturnIntMaxIfOVerflowInt() {
    int result = IntMath.binomial(Integer.MAX_VALUE, 3);
 
    assertEquals(Integer.MAX_VALUE, result);
}

2.2. ceilingPowerOfTwo(int x)

This calculates the value of the smallest power of two which is greater than or equal to x. The result n is such that 2^(n-1) < x < 2 ^n:

@Test
public void whenCeilPowOfTwoInt_shouldReturnResult() {
  int result = IntMath.ceilingPowerOfTwo(20);
 
  assertEquals(32, result);
}

2.3. checkedAdd(int a, int b) and Others

This function calculates the sum of the two parameters. This one provides an additional check which Throws ArithmeticException if the result overflows:

@Test
public void whenAddTwoInt_shouldReturnTheSumIfNotOverflow() {
    int result = IntMath.checkedAdd(1, 2);
 
    assertEquals(3, result);
}

@Test(expected = ArithmeticException.class)
public void whenAddTwoInt_shouldThrowArithmeticExceptionIfOverflow() {
    IntMath.checkedAdd(Integer.MAX_VALUE, 100);
}

Guava has checked methods for three other operators which can overflow: checkedMultiply, checkedPow, and checkedSubtract.

2.4. divide(int p, int q, RoundingMode mode)

This is a simple divide but allows us to define a rounding mode:

@Test
public void whenDivideTwoInt_shouldReturnTheResultForCeilingRounding() {
    int result = IntMath.divide(10, 3, RoundingMode.CEILING);
 
    assertEquals(4, result);
}
    
@Test(expected = ArithmeticException.class)
public void whenDivideTwoInt_shouldThrowArithmeticExIfRoundNotDefinedButNeeded() {
    IntMath.divide(10, 3, RoundingMode.UNNECESSARY);
}

2.5. factorial(int n)

Calculates the factorial value of n. i.e the product of the first n positive integers. Returns 1 if n = 0 and returns Integer.MAX_VALUE if the result does not fit in for int range. The result can be obtained by n x (n-1) x (n-2) x ….. x 2 x 1:

@Test
public void whenFactorialInt_shouldReturnTheResultIfInIntRange() {
    int result = IntMath.factorial(5);
 
    assertEquals(120, result);
}

@Test
public void whenFactorialInt_shouldReturnIntMaxIfNotInIntRange() {
    int result = IntMath.factorial(Integer.MAX_VALUE);
 
    assertEquals(Integer.MAX_VALUE, result);
}

2.6. floorPowerOfTwo(int x)

Returns the largest power of two, of which the results is less than or equal to x. The result n is such that 2^n < x < 2 ^(n+1):

@Test
public void whenFloorPowerOfInt_shouldReturnValue() {
    int result = IntMath.floorPowerOfTwo(30);
 
    assertEquals(16, result);
}

2.7. gcd(int a, int b)

This function gives us the greatest common divisor of a and b:

@Test
public void whenGcdOfTwoInt_shouldReturnValue() {
    int result = IntMath.gcd(30, 40);
    assertEquals(10, result);
}

2.8. isPowerOfTwo(int x)

Returns whether x is a power of two or not. Returns true if the value is a power of two and false otherwise:

@Test
public void givenIntOfPowerTwo_whenIsPowOfTwo_shouldReturnTrue() {
    boolean result = IntMath.isPowerOfTwo(16);
 
    assertTrue(result);
}

@Test
public void givenIntNotOfPowerTwo_whenIsPowOfTwo_shouldReturnFalse() {
    boolean result = IntMath.isPowerOfTwo(20);
 
    assertFalse(result);
}

2.9. isPrime(int n)

This function will tell us if the number passed is prime or not:

@Test
public void givenNonPrimeInt_whenIsPrime_shouldReturnFalse() {
    boolean result = IntMath.isPrime(20);
 
    assertFalse(result);
}

2.10. log10(int x, RoundingMode mode)

This API calculates the base-10 logarithm of the given number. The result is rounded using the provided rounding mode:

@Test
public void whenLog10Int_shouldReturnTheResultForCeilingRounding() {
    int result = IntMath.log10(30, RoundingMode.CEILING);
 
    assertEquals(2, result);
}

@Test(expected = ArithmeticException.class)
public void whenLog10Int_shouldThrowArithmeticExIfRoundNotDefinedButNeeded() {
    IntMath.log10(30, RoundingMode.UNNECESSARY);
}

2.11. log2(int x, RoundingMode mode)

Returns the base-2 logarithm of the given number. The result is rounded using the provided rounding mode:

@Test
public void whenLog2Int_shouldReturnTheResultForCeilingRounding() {
    int result = IntMath.log2(30, RoundingMode.CEILING);
 
    assertEquals(5, result);
}

@Test(expected = ArithmeticException.class)
public void whenLog2Int_shouldThrowArithmeticExIfRoundNotDefinedButNeeded() {
    IntMath.log2(30, RoundingMode.UNNECESSARY);
}

2.12. mean(int x, int y)

With this function we can calculate the mean of two values:

@Test
public void whenMeanTwoInt_shouldReturnTheResult() {
    int result = IntMath.mean(30, 20);
 
    assertEquals(25, result);
}

2.13. mod(int x, int m)

Returns the remainder of integer division of one number by the other:

@Test
public void whenModTwoInt_shouldReturnTheResult() {
    int result = IntMath.mod(30, 4);
    assertEquals(2, result);
}

2.14. pow(int b, int k)

Returns the value of b to the power of k:

@Test
public void whenPowTwoInt_shouldReturnTheResult() {
    int result = IntMath.pow(6, 4);
 
    assertEquals(1296, result);
}

2.15. saturatedAdd(int a, int b) and Others

A sum function with the benefit of controlling any overflows or underflows by returning the value Integer.MAX_VALUE or Integer.MIN_VALUE respectively when it occurs:

@Test:
public void whenSaturatedAddTwoInt_shouldReturnTheResult() {
    int result = IntMath.saturatedAdd(6, 4);
 
    assertEquals(10, result);
}

@Test
public void whenSaturatedAddTwoInt_shouldReturnIntMaxIfOverflow() {
    int result = IntMath.saturatedAdd(Integer.MAX_VALUE, 1000);
 
    assertEquals(Integer.MAX_VALUE, result);
}

There are three other saturated APIs: saturatedMultiply, saturatedPow and saturatedSubtract.

2.16. sqrt(int x, RoundingMode mode)

Returns the square root of the given number. The result is rounded using the provided rounding mode:

@Test
public void whenSqrtInt_shouldReturnTheResultForCeilingRounding() {
    int result = IntMath.sqrt(30, RoundingMode.CEILING);
 
    assertEquals(6, result);
}

@Test(expected = ArithmeticException.class)
public void whenSqrtInt_shouldThrowArithmeticExIfRoundNotDefinedButNeded() {
    IntMath.sqrt(30, RoundingMode.UNNECESSARY);
}

3. LongMath Utility

LongMath has utilities for Long values. Most operations are similar to the IntMath utility, with an exceptional few described here.

3.1. mod(long x, int m) and mod(long x, long m)

Returns the x mod m. The remainder of integer division of x by m:

@Test
public void whenModLongAndInt_shouldModThemAndReturnTheResult() {
    int result = LongMath.mod(30L, 4);
 
    assertEquals(2, result);
}
@Test
public void whenModTwoLongValues_shouldModThemAndReturnTheResult() {
    long result = LongMath.mod(30L, 4L);
 
    assertEquals(2L, result);
}

4. BigIntegerMath Utility

BigIntegerMath is used to perform mathematical operations on type BigInteger.

This utility has some methods similar to the IntMath.

5. DoubleMath Utility

DoubleMath utility is used to perform an operation on double values.

Similar to the BigInteger utility, the number of available operations is limited and share similarity with IntMath utility. We will list some exceptional functions available only to this utility class.

5.1. isMathematicalInteger(double x)

Returns whether x is a mathematical integer. It checks if the number can be represented as an integer without a data loss:

@Test
public void givenInt_whenMathematicalDouble_shouldReturnTrue() {
    boolean result = DoubleMath.isMathematicalInteger(5);
 
    assertTrue(result);
}

@Test
public void givenDouble_whenMathematicalInt_shouldReturnFalse() {
    boolean result = DoubleMath.isMathematicalInteger(5.2);
 
    assertFalse(result);
}

5.2. log2(double x)

Calculates the base-2 logarithm of x:

@Test
public void whenLog2Double_shouldReturnResult() {
    double result = DoubleMath.log2(4);
 
    assertEquals(2, result, 0);
}

6. Conclusion

In this quick tutorial, we explored some useful Guava maths utility functions.

As always, the source code can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!