VOOZH about

URL: https://www.baeldung.com/guava-math

⇱ Guide to Mathematical Utilities in Guava | Baeldung


πŸ‘ Image
eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
πŸ‘ announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
πŸ‘ announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
πŸ‘ announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
πŸ‘ announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
πŸ‘ announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
eBook – HTTP Client – NPI EA (cat=Http Client-Side)
πŸ‘ announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
πŸ‘ announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
πŸ‘ announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
πŸ‘ announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
πŸ‘ announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
πŸ‘ announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New β€œREST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
πŸ‘ announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
πŸ‘ announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
πŸ‘ announcement - icon

Refactor Java code safely β€” and automatically β€” with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β€” one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
πŸ‘ announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
πŸ‘ announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
πŸ‘ announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
πŸ‘ announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
πŸ‘ announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
πŸ‘ announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

πŸ‘ announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
πŸ‘ announcement - icon

Modern Java teams move fast β€” but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural β€” and as fast β€” as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)