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

In this tutorial, we’ll explore calculating the sum of the first N even numbers divisible by 3 using Java. This can be solved using different approaches.

We’ll examine two distinct methods to illustrate these approaches. The first method is the brute force method. This method involves a step-by-step approach where we discuss each even number and determine its divisibility by 3. While simple to understand, it may not be the most efficient for large values of N. The second method we’ll discuss is the optimized mathematical approach. This method leverages the inherent properties of even numbers divisible by 3 to derive a formula for direct calculation. This approach offers significant performance improvements, especially when dealing with large datasets of numbers.

2. Brute Force Method

The brute-force method involves iterating through numbers, identifying those that are even and divisible by 3, and adding them to a running total. This is a straightforward approach, but it may be inefficient because it checks every even number individually, rather than focusing directly on multiples of 6. Since any number divisible by 2 and 3 is also divisible by 6 (as 6 is the least common multiple of 2 and 3), focusing on multiples of 6 allows us to skip unnecessary checks for numbers that don’t meet both conditions.

2.1. Implementation with for Loop

For our code examples, we’ll define NUMBER as 7, which represents the first 7 even numbers, and EXPECTED_SUM as 18 (6 + 12), which is the expected result of this calculation:

static final int NUMBER = 7;
static final int EXPECTED_SUM = 18;

In the next example, we’ll use a for loop to achieve the result:

@Test
void givenN_whenUsingBruteForceForLoop_thenReturnsCorrectSum() {
    int sum = 0;

    for (int i = 2; i <= NUMBER * 2; i++) {
        if (i % 2 == 0 && i % 3 == 0) {
            sum += i;
        }
    }

    assertEquals(EXPECTED_SUM, sum);
}

Here, we check each even number starting from 2, and the loop continues until we’ve identified the first N numbers divisible by both 2 and 3. The time complexity is O(N) since we iterate until we find N numbers. In this case, we check many numbers that aren’t divisible by 2 and 3.

2.2. Functional Programming Approach

We can leverage Java’s functional programming features for a more modern approach. Using the Stream API, we can generate an infinite Stream of numbers,  then filter this Stream to include only even numbers, limit it to the first N even numbers, and finally filter those that are divisible by 3 before summing them. This functional style can be more concise and declarative:

@Test
void givenN_whenUsingFunctionalApproach_thenReturnsCorrectSum() {
    int sum = IntStream.iterate(2, i -> i + 1)
      .filter(i -> i % 2 == 0)
      .limit(NUMBER)
      .filter(i -> i % 3 == 0)
      .sum();

    assertEquals(EXPECTED_SUM, sum);
}

This implementation uses IntStream.iterate() to generate an infinite Stream of Integers starting from 2. This approach isn’t only concise but also inherently parallelizable if necessary.

2.3. Improved Brute Force Method

The brute-force method can be further improved by observing that even numbers divisible by 3 are also divisible by 6. This means that instead of checking every even number, we can directly check numbers that are multiples of 6. This optimization reduces the number of checks we need to perform, making the method more efficient:

@Test
void givenN_whenUsingImprovedBruteForce_thenReturnsCorrectSum() {
    int sum = IntStream.iterate(6, i -> i + 6)
      .limit(NUMBER / 3)
      .sum();

    assertEquals(EXPECTED_SUM, sum);
}

By directly iterating through multiples of 6, we improve the performance of the brute-force method, making it more efficient without changing its core structure. This optimization makes the algorithm faster in practice, but the overall time complexity remains linear because the number of iterations is directly proportional to N.

3. Optimized Mathematical Approach

In the brute-force methods, we iterated through numbers and checked whether each was divisible by 6 to find even numbers divisible by 3. While effective, these approaches can be further optimized by leveraging the mathematical insight that the numbers we’re summing are multiples of 6. Therefore, instead of iterating through numbers and checking divisibility conditions, we can directly calculate the first N/3 multiples of 6 and sum them. This is because, out of every three even numbers, only one will be divisible by 3, so the first N even numbers divisible by 3 are the first N/3 multiples of 6.

3.1. Mathematical Insight

  • Every even number divisible by 3 is a multiple of 6.
  • Instead of iterating through numbers, we can directly calculate the first N multiples of 6 and sum them.
  • The first N multiples of 6 are 6 * 1, 6 * 2, 6 * 3, …, 6 * N. Therefore, we can calculate the sum as follows:
    Sum = 6 * (1 + 2 + 3 + ⋯ + N)
  • The sum of the first N natural numbers is given by the formula:
    (N * (N + 1)) / 2
  • Using this formula, the sum of the first N/3 multiples of 6 can be computed as:
    Sum = 6 * (N / 3 * (N / 3 + 1)) / 2 = 3 * (N / 3) * (N / 3 + 1)

This approach avoids looping altogether, making it more efficient than brute-force methods, especially for large values of N.

3.2. Optimized Mathematical Code

We directly calculate the sum using the formula for the sum of the first N / 3 multiples of 6:

@Test
void givenN_whenUsingOptimizedMethod_thenReturnsCorrectSum() {
    int sum = 3 * (NUMBER / 3) * (NUMBER / 3 + 1);

    assertEquals(EXPECTED_SUM, sum);
}

This approach is much faster because it avoids looping altogether and reduces the problem to a simple arithmetic calculation. The time complexity of this approach is O(1), as it performs a constant number of operations, regardless of the value of N.

4. Comparing the Two Approaches

The brute-force methods and the optimized mathematical approach differ mainly in performance, simplicity, and flexibility.

In terms of time complexity, the brute-force methods have a complexity of O(N), as they require iterating over numbers. Even the improved brute-force method, while more efficient, still depends on looping. On the other hand, the optimized mathematical approach uses a direct formula, giving it a constant time complexity of O(1), making it significantly faster, especially for large N.

Regarding simplicity, the brute-force methods are straightforward but involve loops and conditions, making them slightly longer and more involved. The optimized method is much cleaner and more concise, as it directly applies a formula. However, it requires some familiarity with mathematical principles.

When it comes to flexibility, the brute-force methods are more adaptable. If the problem changes, like summing numbers divisible by a different number, these methods can easily be adjusted. The optimized approach, however, is specialized for multiples of 6 and would need a new formula for different conditions.

The following table provides a concise summary of the key differences:

Brute Force Improved Brute Force Optimized Mathematical
Time Complexity O(N) O(N) O(1)
Space Complexity O(1) O(1) O(1)
Simplicity Easy, loop-based More efficient loop Very concise, uses a formula
Flexibility Adaptable to different conditions Adaptable to different conditions Less adaptable, formula-specific

5. Conclusion

In this article, we explored two main approaches for calculating the sum of the first N even numbers divisible by 3: brute-force methods and an optimized mathematical approach. The brute-force approach, though adaptable, involves iterating through numbers with O(N) complexity. At the same time, the optimized method uses a direct formula with constant time, O(1), offering better efficiency but less flexibility.

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)