Brute Force
Checking every option is an algorithm too
Brute force is the most direct way to solve a problem: examine every valid option one by one and choose the one that satisfies the condition. This approach is sometimes considered too simple, but it is often the best place to start: it is easy to verify, easy to understand, and frequently solves the problem completely.
For example, suppose you need to find the first number from 1 to 100 that is divisible by both 7 and 9. Instead of trying to invent a special formula, you can simply check the numbers in order.
int answer = -1;
for (int value = 1; value <= 100; value++) {
if (value % 7 == 0 && value % 9 == 0) {
answer = value;
break;
}
}
The loop examines candidates one by one. As soon as the first suitable value is found,
the search can stop with break.
What exactly should be enumerated
The main question in brute force is not “which loop should I write?” but “what is a candidate?”. It can be a number from a range, an array element, a pair of elements, or one of several predefined options. After that, you need a simple test for each candidate.
For example, if you need to find all two-digit numbers whose digits add up to 10, the candidates are the numbers from 10 to 99, and the condition is checking the sum of the two digits.
for (int number = 10; number <= 99; number++) {
int tens = number / 10;
int ones = number % 10;
if (tens + ones == 10) {
System.out.println(number);
}
}
When to stop the search
If the problem asks for the first suitable option or only asks whether at least one such option exists, there is usually no reason to keep searching after success. An early exit makes the intention of the code clearer and avoids unnecessary work.
If you need to find all suitable values, count them, or choose the best result among them, the iteration must continue to the end.