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)
announcement - icon

Do JSON right with Jackson

Download the E-book

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.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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

When working with large numbers, intermediate results can exceed data type limits. For such scenarios, modular arithmetic helps keep numbers manageable and prevent overflow errors.

In this tutorial, we’ll learn how to perform modulo-arithmetic operations with 10^9 + 7 as an example format for the modulus.

2. Basics

In this section, let’s brush up on a few important concepts to help us perform modular arithmetic operations efficiently.

2.1. Symmetric Modulo and Non-negative Remainder

Let’s imagine that we want to compute a mod b. By applying the division algorithm, we can get the positive remainder (r):

a = q.b + r
where, b>0 and r≧0

We must note that we’ll assume that modulus (b) is a positive number for the scope of this article.

Subsequently, we can rewrite the equation to get a negative remainder:

a = (q+1)b - (b - r)
where, -(b-r)≦0

From a purely mathematical point of view, this is called symmetric modulo, where the remainder lies in the range [-b, b). However, most programming implementations prefer the non-negative remainder in the range [0, b) when returning the result of the modulo operation for a positive modulus.

2.2. Congruence Property

Now, let’s see another interesting property in modular arithmetic that deals with congruence relation ():

(a mod n) = (b mod n) <=> a≡b (mod n)

Essentially, two numbers, a and b, are congruent modulo n, if they give the same remainder when divided by n. As a result, we can say that 10 ≡ 4 (mod 3).

2.3. Strategy for Modular Arithmetic

Using the symmetric modulo and congruence properties, we can formulate a strategy for modular arithmetic operations by choosing a smaller intermediate result amongst two numbers whenever feasible.

For this purpose, let’s define the minSymmetricMod() method that returns the remainder that has a lower absolute value:

static int minSymmetricMod(int x) {
    if (Math.abs(x % MOD) <= Math.abs((MOD - x) % MOD)) {
        return x % MOD;
    } else {
        return -1 * ((MOD - x) % MOD);
    }
}

As part of our strategy, we’ll use minSymmetricMod() to compute all the intermediate results.

Further, let’s define the mod() method that’s guaranteed to give a positive remainder value:

static int mod(int x) {
    if (x >= 0) {
        return x % MOD;
    } else {
        return mod(MOD + x);
    }
}

We can use method overloading to support long values.

For our use cases, we’re using MOD = 10^9 + 7. However, unless stated otherwise, the general principle holds true for any other modulus value.

We’ll apply these concepts to addition, subtraction, multiplication, and other modular arithmetic operations.

3. Modular Sum

In this section, we’ll learn to do the modulo sum operation efficiently.

3.1. Distributive Property

The modulo operation follows distributive property over addition:

(a + b) mod n = ((a mod n) + (b mod n)) mod n

Further, we can use the symmetric_mod for all the intermediate modulo operators:

(a + b) mod n = ((a symmetric_mod n) + (b symmetric_mod n)) mod n

The outermost mod operation guarantees a positive remainder. In contrast, the inner symmetric_mod operations reduce the magnitude of the numbers by appropriately choosing the lower of the positive or negative remainders.

3.2. Computation

We can write the modAdd() method to compute the modulo sum of two numbers:

static int modSum(int a, int b) {
    return mod(minSymmetricMod(a) + minSymmetricMod(b));
}

Now, let’s validate our approach by computing modulo sum for a few pairs of numbers:

assertEquals(1000000006, modSum(500000003, 500000003));
assertEquals(1, modSum(1000000006, 2));
assertEquals(999999999, modSum(999999999, 0));
assertEquals(1000000005, modSum(1000000006, 1000000006));

Perfect! We’ve got the right results.

4. Modular Subtraction

Now that we’ve discussed modulo addition operation, we can extend our approach to modulo subtraction in this section.

4.1. Distributive Property

Let’s start by looking at the distributive property of modulo operation over subtraction:

(a - b) mod n = ((a mod n) - (b mod n)) mod n

Further, let’s apply our strategy of using the symmetric_mod operation for the intermediate results:

(a - b) mod n = ((a symmetric_mod n) - (b symmetric_mod n)) mod n

That’s it. We’re now ready to implement this approach for computing modulo subtraction.

4.2. Computation

Let’s write the modSubtract() method to compute the modulo subtraction of two numbers:

static int modSubtract(int a, int b) {
    return mod(minSymmetricMod(a) - minSymmetricMod(b));
}

Under the hood, minSymmetricMod() ensures that the magnitude of intermediate terms is kept as small as possible.

Next, we must test our implementation against different sets of numbers:

assertEquals(0, modSubtract(500000003, 500000003));
assertEquals(1000000005, modSubtract(1, 3));
assertEquals(999999999, modSubtract(999999999, 0));

Great! The result looks correct.

5. Modular Multiplication

In this section, let’s learn how to compute the modular multiplication of two numbers.

5.1. Distributive Property

Like addition, the modulo operation is also distributive over multiplication:

(a * b) mod n = ((a mod n) * (b mod n)) mod n

As a result, we can use the symmetric_mod operation for intermediate terms:

(a * b) mod n = ((a symmetric_mod n) * (b symmetric_mod n)) mod n

For all intermediate results, we’ll choose the remainder with a lower absolute value. Eventually, we’ll apply the mod operation to get a positive remainder.

5.2. Computation

Let’s write the modMultiply() method to compute the modulo multiplication of two numbers:

static long modMultiply(int a, int b) {
    int result = minSymmetricMod((long) minSymmetricMod(a) * (long) minSymmetricMod(b));
    return mod(result);
}

Although the upper bound on the return value of minSymmetricMod() is MOD – 1, the resulting value after multiplication could overflow the limit of the Integer data type. So, we must use a (long) type casting for multiplication.

Further, let’s test our implementation against a few pairs of numbers:

assertEquals(1, modMultiply(1000000006, 1000000006));
assertEquals(0, modMultiply(999999999, 0));
assertEquals(1000000006, modMultiply(500000003, 2));
assertEquals(250000002, modMultiply(500000003, 500000003));

Excellent! It looks like we nailed this one.

6. Modular Exponential

In this section, we’ll extend our approach of modulo multiplication computation to calculate modulo power.

6.1. Modular Exponential Property

Since modulo is distributive over multiplication, we can simplify the modular exponentiation:

(a ^ b) mod n = ((a mod n) ^ b) mod n

We must note that modulo isn’t distributive over the power operation as we didn’t take modulo for the exponent, b.

Like earlier, we can replace the mod for intermediate terms with the symmetric_mod operation:

(a ^ b) mod n = ((a symmetric_mod n) ^ b) mod n

We’ll use this property for computation purposes.

6.2. Computation

Let’s go ahead and write the modPower() method that takes two parameters, namely, base and exp:

static int modPower(int base, int exp) {
    int result = 1;
    int b = base;
    while (exp > 0) {
        if ((exp & 1) == 1) {
            result = minSymmetricMod((long) minSymmetricMod(result) * (long) minSymmetricMod(b));
        }
        b = minSymmetricMod((long) minSymmetricMod(b) * (long) minSymmetricMod(b));
        exp >>= 1;
    }
    return mod(result);
}

We used the fast power approach to calculate the exponential value while using minSymmetricMod() for intermediate modulo values. Additionally, we did a (long) typecast to hold the multiplication result, which could be larger than the Integer.MAX_VALUE value.

Now, let’s see our implementation in action by verifying it for different pairs of numbers:

assertEquals(16, modPower(2, 4));
assertEquals(1, modPower(2, 0));
assertEquals(1000000006, modPower(1000000006, 1));
assertEquals(1000000006, modPower(500000003, 500000003));
assertEquals(500000004, modPower(500000004, 500000004));
assertEquals(250000004, modPower(500000005, 500000005));

Fantastic! Our approach is highly performant and gives correct results.

7. Modular Multiplicative Inverse

The modulo multiplicative inverse of a mod m exists if and only if a and m are co-prime. For our scenario, m=10^9 + 7 is a prime number, which is co-prime with all other numbers, so let’s learn how to find the modular multiplication inverse.

7.1. Bézout’s Identity

According to Bézout’s Identity, we can express gcd(a, b) using two coefficients, x and y:

gcd(a, b) = x*a + y*b

Interestingly, when a and b are co-primes, we can replace gcd(a, b) with 1:

x*a + y*b = 1

Now, let’s apply the mod b operation on both sides of the equation:

(x*a + y*b) % b = 1 % b
=> (x*a) % b = 1

We’ve arrived at the definition of modular multiplicative inverse that states (a-1 * a) % b = 1.

The problem of finding the modular multiplicative inverse boils down to finding Bézout’s coefficient (x). Therefore, we can use the extended Euclidean algorithm to solve our use case.

7.2. Computation With Extended Euclidean Algorithm

Let’s write the extendedGcd() method that returns the greatest common divisor and Bézout’s coefficients:

static int[] extendedGcd(int a, int b) {
    if (b == 0) {
        return new int[] { a, 1, 0 };
    }
    int[] result = extendedGcd(b, a % b);
    int gcd = result[0];
    int x = result[2];
    int y = result[1] - (a / b) * result[2];
    return new int[] { gcd, x, y };
}

As a result, we can now find the modular multiplicative inverse using the extendedGCD() and mod() methods:

static int modInverse(int a) {
    int[] result = extendedGcd(a, MOD);
    int x = result[1];
    return mod(x);
}

Lastly, we must test our implementation for a few numbers:

assertEquals(500000004, modInverse(2));
assertEquals(1, modInverse(1));
assertEquals(1000000006, modInverse(1000000006));
assertEquals(1000000005, modInverse(500000003));

The result looks correct.

8. Modular Division

Modular multiplication and modular inverse are prerequisites to understanding the modular division operation. Further, we can perform modular division only when modular inverse exists.

For two co-prime numbers, a and b, let’s write the modDivide() method to compute modular division:

static int modDivide(int a, int b) {
    return mod(modMultiply(a, modInverse(b)));
}

If we notice clearly, it’s equivalent to the modular multiplication of a and the modular inverse of b.

Now, let’s see modular division in action for some of the sample numbers:

assertEquals(500000004, modDivide(1, 2));
assertEquals(2, modDivide(4, 2));
assertEquals(1000000006, modDivide(1000000006, 1));

It looks like we’ve got this one right.

9. Conclusion

In this article, we learned about the modular arithmetic operations for sum, multiplication, subtraction, power, inverse, and division. Further, we learned that modular multiplicative inverse and division operations are only possible for co-prime numbers.

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)