How to Use Guava's Math Utilities: IntMath, LongMath, and BigIntegerMath

Guava's math utilities provide overflow-safe arithmetic, rounding-mode aware division, and combinatorial operations for int, long, and BigInteger types through the static classes IntMath, LongMath, and BigIntegerMath in the com.google.common.math package.

The google/guava library extends Java's standard mathematical capabilities with production-grade utilities designed to prevent integer overflow and support precise rounding control. Guava's math utilities target the three primary integer representations—primitive int, primitive long, and arbitrary-precision BigInteger—through immutable, stateless utility classes that implement algorithms from Hacker's Delight for maximum performance.

Core Classes in the Math Package

The com.google.common.math package organizes functionality into three final classes with private constructors, enforcing static usage patterns:

  • IntMath – Located in IntMath.java, this class provides safe int arithmetic including checked addition, saturated multiplication, binomial coefficients, factorials, and base-2 logarithms. It delegates prime testing operations to LongMath.
  • LongMath – Implemented in LongMath.java, this class mirrors the IntMath API across the 64-bit long range and adds Miller-Rabin primality testing via the isPrime(long) method.
  • BigIntegerMath – Found in BigIntegerMath.java, this class offers unlimited-precision mathematics including sqrt, log2, and power operations that accept RoundingMode parameters while relying on java.math.BigInteger for underlying calculations.

Overflow-Safe Arithmetic Operations

All three classes provide overflow-aware APIs that eliminate ambiguity when calculations exceed type limits. The utilities offer two distinct safety strategies:

  • Checked operations – Methods like checkedAdd, checkedMultiply, and checkedPow throw an ArithmeticException immediately when detecting overflow.
  • Saturated operations – Methods like saturatedAdd and saturatedMultiply return Integer.MAX_VALUE or Integer.MIN_VALUE (and their long equivalents) instead of throwing, matching the behavior of Google’s C++ math utilities.

In IntMath.java, the binomial(int n, int k) method exemplifies this safety by returning Integer.MAX_VALUE when the result overflows, while LongMath.factorial(int n) returns Long.MAX_VALUE for out-of-range results.

Rounding-Mode Aware Division and Roots

Unlike Java’s standard division operators, Guava’s math utilities accept java.math.RoundingMode arguments to specify exact rounding behavior. The divide(int, int, RoundingMode) method in IntMath.java and its counterparts in LongMath and BigIntegerMath implement the same rounding rules as java.math.BigDecimal.

Available rounding strategies include CEILING, FLOOR, DOWN, UP, HALF_EVEN, HALF_UP, and HALF_DOWN. For example, dividing 7 by 3 with RoundingMode.CEILING yields 3, while RoundingMode.FLOOR yields 2.

Combinatorial and Logarithmic Functions

The utilities provide optimized implementations of computationally expensive operations:

  • factorial(int n) – Computes n! with overflow checking, available in all three classes.
  • binomial(int n, int k) – Calculates binomial coefficients using multiplicative formulas that avoid intermediate overflow where possible.
  • log2(int x, RoundingMode mode) – Computes base-2 logarithms with specified rounding, implemented using bit manipulation tricks from IntMath.java and LongMath.java.
  • sqrt(BigInteger x, RoundingMode mode) – Provides integer square roots with exact rounding control in BigIntegerMath.java.

Practical Code Examples

import com.google.common.math.IntMath;
import com.google.common.math.LongMath;
import com.google.common.math.BigIntegerMath;
import java.math.BigInteger;
import java.math.RoundingMode;

// 1. Basic overflow-checked arithmetic with int
int a = Integer.MAX_VALUE - 10;
int b = 20;
int sum = IntMath.checkedAdd(a, b); // throws ArithmeticException

// 2. Compute a binomial coefficient safely
int binom = IntMath.binomial(30, 5); // Returns Integer.MAX_VALUE if overflow occurs

// 3. Rounding division with specific mode
int ceilDiv = IntMath.divide(7, 3, RoundingMode.CEILING); // → 3

// 4. Long-wide factorial with overflow handling
long fact20 = LongMath.factorial(20); // Returns actual value or Long.MAX_VALUE if overflow

// 5. Prime testing for long values
boolean isPrime = LongMath.isPrime(1_000_003L); // Miller-Rabin implementation

// 6. Unlimited-precision operations
BigInteger big = new BigInteger("12345678901234567890");
BigInteger sqrt = BigIntegerMath.sqrt(big, RoundingMode.FLOOR);
BigInteger pow = BigIntegerMath.pow(BigInteger.valueOf(2), 100); // 2^100

Source Implementation Details

The concrete implementations in the google/guava repository reveal performance optimizations and safety checks:

  • IntMath.java – Uses branch-free bit tricks like lessThanBranchFree and isPowerOfTwo for speed. All public methods validate inputs via MathPreconditions before performing calculations.
  • LongMath.java – Implements Miller-Rabin primality testing with deterministic bases for 64-bit values. The factorial method switches to precomputed tables for small inputs.
  • BigIntegerMath.java – Delegates heavy computation to java.math.BigInteger while adding rounding logic that mirrors the primitive math classes, ensuring API consistency across type boundaries.

Summary

  • Guava's math utilities in com.google.common.math provide IntMath, LongMath, and BigIntegerMath for type-specific arithmetic.
  • Overflow handling comes in two flavors: checked (throws exception) and saturated (returns max/min value).
  • Rounding control via RoundingMode parameters enables precise division and root operations consistent with BigDecimal semantics.
  • Performance optimizations include bit-level tricks from Hacker's Delight and precomputed tables for factorials.
  • Thread safety is guaranteed by final classes with static methods and no mutable state.

Frequently Asked Questions

What is the difference between checked and saturated arithmetic in Guava?

Checked operations like IntMath.checkedAdd() throw an ArithmeticException when overflow is detected, immediately signaling calculation errors. Saturated operations like IntMath.saturatedAdd() return the maximum or minimum value for the type (Integer.MAX_VALUE or Integer.MIN_VALUE) instead of throwing, allowing computations to continue with boundary values.

Which Guava math class should I use for my data type?

Use IntMath when working with int values that require fast operations without boxing overhead. Choose LongMath when values might exceed the 32-bit int range but fit within 64-bit long primitives, especially for prime testing or larger combinatorial calculations. Select BigIntegerMath when dealing with arbitrarily large integers such as cryptographic keys or massive combinatorial results that exceed long capacity.

How do rounding modes work in Guava's division methods?

Guava's divide methods in all three classes accept a java.math.RoundingMode parameter that specifies how to handle fractional results. For example, RoundingMode.CEILING always rounds toward positive infinity, while RoundingMode.HALF_UP rounds toward the nearest neighbor unless both neighbors are equidistant, in which case it rounds up. These implementations follow the exact same rounding rules as java.math.BigDecimal according to the source code in IntMath.java and BigIntegerMath.java.

Are Guava's math classes thread-safe?

Yes. IntMath, LongMath, and BigIntegerMath are all declared as final with private constructors, exposing only static methods that operate on immutable inputs. Because they maintain no instance state, these classes are inherently thread-safe and can be used concurrently without synchronization overhead.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →