Standard Numeric Algorithms
The loop-and-decision patterns every programmer reuses: testing divisibility, extracting the digits of an integer, counting how often a condition holds, finding a maximum or minimum, and computing sums and averages.
Many problems turn out to be variations of a few standard algorithms built from iteration and selection. There are standard algorithms to identify if an integer is or is not evenly divisible by another integer, identify the individual digits in an integer, determine the frequency with which a specific criterion is met, determine a minimum or maximum value, and compute a sum or average. Learning these patterns well means that most new problems can be solved by recognizing which pattern applies and adapting it.
1Divisibility
An integer n is evenly divisible by d when dividing leaves no remainder, which in Java is the test n % d == 0. This single expression answers many questions: whether a number is even (n % 2 == 0), whether a year number is a multiple of 4, or whether d is a divisor of n.
Placed inside a loop, the test becomes an algorithm. Looping d from 1 to n and counting the values for which n % d == 0 counts the divisors of n; a number with exactly two divisors, 1 and itself, is prime. The remainder operator is used here with positive values only, which is where its behavior is simplest.
n is evenly divisible by d exactly when n % d == 0.| Algorithm | Key idea | Core code |
|---|---|---|
| Divisibility | Remainder is zero | if (n % d == 0) |
| Individual digits | Last digit, then remove it | d = n % 10; n /= 10; |
| Frequency | Counter increases when a criterion holds | if (test) { count++; } |
| Maximum / minimum | Keep the best so far; replace when beaten | if (v > max) { max = v; } |
| Sum / average | Accumulate; divide as double | sum += v; ... (double) sum / count |
Counting Divisors and Testing for Prime
Count the divisors of 36, then decide whether 37 is prime (exactly two divisors).
public static int countDivisors(int n)
{
int count = 0;
for (int d = 1; d <= n; d++)
{
if (n % d == 0)
{
count++;
}
}
return count;
}
9
true
false
- 1The test.
n % d == 0istrueexactly whenddividesnevenly. - 236. Divisors 1, 2, 3, 4, 6, 9, 12, 18, 36: nine of them.
- 337. Only 1 and 37 divide it, so the count is 2 and 37 is prime.
- 439. 3 × 13 = 39, so it has four divisors: not prime.
n % d == 0 inside a loop is the standard algorithm for divisibility questions.2Identifying Individual Digits
For a non-negative integer, n % 10 is its last digit and n / 10 is the number with that digit removed, because integer division drops the remainder. Repeating these two steps in a loop visits every digit from right to left, and the loop ends when n becomes 0.
The digit loop is a template for many tasks: adding the digits, counting them, counting how many are odd, finding the largest, or building a new number. To build the reversed number, multiply the result so far by 10 and add each digit; to keep the digits in their original order, a different approach is needed, since they come out last digit first.
n % 10 gives the last digit of a non-negative integer and n / 10 removes it, so a loop can visit every digit.Sum and Count of the Digits
Find the sum of the digits of 4719 and how many digits it has.
int n = 4719;
int sum = 0;
int digits = 0;
while (n > 0)
{
sum += n % 10;
n /= 10;
digits++;
}
System.out.println(sum + " " + digits);
21 4
- 1Each pass adds the last digit (
n % 10) and then removes it (n /= 10). - 2Digits visited: 9, 1, 7, 4, so the sum is 21 and there are 4 passes.
- 3Stopping. After the fourth pass
nis 0, and0 > 0isfalse.
% 10 and / 10 identifies the individual digits in an integer, from right to left.| Pass | n before | n % 10 | reversed | n after |
|---|---|---|---|---|
| 1 | 4719 | 9 | 0 × 10 + 9 = 9 | 471 |
| 2 | 471 | 1 | 9 × 10 + 1 = 91 | 47 |
| 3 | 47 | 7 | 91 × 10 + 7 = 917 | 4 |
| 4 | 4 | 4 | 917 × 10 + 4 = 9174 | 0 |
Reversing a Number
Build the number with the digits of 4719 in reverse order.
int n = 4719;
int reversed = 0;
while (n > 0)
{
int digit = n % 10;
reversed = reversed * 10 + digit;
n /= 10;
}
System.out.println(reversed);
9174
- 1Shift and add. Multiplying
reversedby 10 makes room for the next digit on the right. - 2Trace: 0 → 9 → 91 → 917 → 9174.
Once n reaches 0, n / 10 is still 0, so a condition of n >= 0 never becomes false. Digit loops use n > 0. (Note that the loop then makes no passes for n == 0 itself, a special case to handle separately if needed.)
3Determining a Frequency
To find how often a criterion is met, combine a loop that visits every candidate with an if statement that tests the criterion, and a counter that increases only when the test is true. The counter starts at 0 before the loop. After the loop, it holds the frequency.
The criterion can be any Boolean expression: divisibility, a range check, a property of the digits, or a compound condition. This pattern is so common that it is worth recognizing instantly: whenever a question begins "how many," expect a counter, a loop, and an if.
How Often Is a Criterion Met?
Count the multiples of 7 from 1 to 100, and the numbers from 1 to 50 whose digit sum is 5.
int sevens = 0;
for (int k = 1; k <= 100; k++)
{
if (k % 7 == 0)
{
sevens++;
}
}
int fives = 0;
for (int k = 1; k <= 50; k++)
{
int digitSum = k / 10 + k % 10;
if (digitSum == 5)
{
fives++;
}
}
System.out.println(sevens + " " + fives);
14 6
- 1The pattern. A counter starts at 0, a loop visits every candidate, and an
ifadds 1 only when the criterion holds. - 2Multiples of 7. 7, 14, …, 98: 14 values.
- 3Digit sum 5. For two-digit values,
k / 10is the tens digit andk % 10the ones digit: 5, 14, 23, 32, 41, 50, six values.
A counter declared or set to 0 inside the loop body starts over on every pass, so it can never exceed 1. Initialize counters before the loop, and increase them inside the if.
4Determining a Maximum or Minimum
To find the largest value, keep a variable holding the largest value seen so far. Compare each new value with it, and replace it when the new value is larger. When every value has been compared, the variable holds the maximum. A minimum works the same way with the comparison reversed.
The starting value matters. Initializing the tracker with the first actual value is always safe, because that value is a genuine candidate. Initializing a maximum to 0 fails when every value is negative; if a fixed starting value is used, Integer.MIN_VALUE for a maximum or Integer.MAX_VALUE for a minimum works because any real value will replace it. To report where the extreme occurred, update a second variable holding its position at the same time.
The Largest and Smallest Digit
Find the largest and smallest digit of 4719.
int n = 4719;
int largest = n % 10;
int smallest = n % 10;
n /= 10;
while (n > 0)
{
int d = n % 10;
if (d > largest)
{
largest = d;
}
if (d < smallest)
{
smallest = d;
}
n /= 10;
}
System.out.println(largest + " " + smallest);
9 1
- 1Start with an actual value. Both trackers begin as the first digit, 9, which is guaranteed to be a real candidate.
- 2Compare each remaining digit: 1 lowers the minimum; 7 and 4 change nothing.
- 3Two separate
ifstatements, because a single value could in principle update both.
Where Is a Value Smallest?
For whole numbers x from 0 to 10, find the smallest value of x² − 8x + 20 and the x where it occurs.
int bestX = 0;
int bestValue = 0 * 0 - 8 * 0 + 20;
for (int x = 1; x <= 10; x++)
{
int value = x * x - 8 * x + 20;
if (value < bestValue)
{
bestValue = value;
bestX = x;
}
}
System.out.println("min " + bestValue + " at x = " + bestX);
min 4 at x = 4
- 1Initialize with the first case, x = 0, whose value is 20.
- 2Values for x = 1 to 10: 13, 8, 5, 4, 5, 8, 13, 20, 29, 40.
- 3Track both. When a new minimum is found, record its value and its x together.
If the values are −8, −3, and −12, a maximum initialized to 0 stays 0, which is not one of the values. Begin with the first value, or with Integer.MIN_VALUE, so that the true maximum always replaces the starting value.
5Computing a Sum or Average
A sum uses an accumulator that starts at 0 and adds each value in turn. An average needs both a sum and a count of the values, and is the sum divided by the count. When both are int variables, that division truncates, so the average must be computed as (double) sum / count, casting before dividing.
If the count could be 0, dividing would fail for integers or produce a meaningless result for doubles, so a program averaging an unknown number of values should check that the count is positive first. Sums of many large values can also exceed the range of int; for the sizes used in most problems this is not an issue, but it is worth remembering.
int values truncates, so cast to double first.An Average That Keeps Its Fraction
Find the sum and average of the whole numbers from 1 to 4.
int sum = 0;
int count = 0;
for (int k = 1; k <= 4; k++)
{
sum += k;
count++;
}
System.out.println(sum);
System.out.println(sum / count);
System.out.println((double) sum / count);
10
2
2.5
- 1Two accumulators.
sumadds each value;countadds 1 per value. - 2Integer division.
10 / 4is 2, losing the fraction. - 3Cast first.
(double) sum / countconvertssumbefore dividing: 2.5.
double before the division.| Mistake | Effect | Fix |
|---|---|---|
| Initializing a maximum to 0 | Wrong when every value is negative | Start with the first value (or Integer.MIN_VALUE) |
| Using else if for max and min together | A value that should update both updates only one | Use two separate if statements |
| Dividing int sum by int count | Average loses its fraction | (double) sum / count |
| Digit loop with n >= 0 | Infinite loop: 0 / 10 is still 0 | Use n > 0 |
6Combining the Patterns
Real problems often combine several patterns in one loop. Finding the average of the even numbers in a range uses a frequency counter, a divisibility test, and a sum together. Finding the number with the largest digit sum in a range nests the digit algorithm inside a maximum algorithm. The patterns are building blocks, and recognizing them inside a larger task is the key skill.
When designing such an algorithm, decide which accumulators are needed and initialize all of them before the loop; decide what the loop visits; and then decide, for each value, which tests to apply and which accumulators to update. Writing these decisions in plain words first makes the code almost write itself.
When tracking both a maximum and a minimum, write two separate if statements. With else if, a value that updates the maximum is never checked against the minimum, which can leave the minimum wrong, for example when the first value is both the largest and smallest so far.
Four Habits for Numeric Algorithms
1. % for Divisibility and Digits
n % d == 0 tests divisibility; n % 10 is the last digit.
2. Counters Start at 0
Before the loop; increase inside the if.
3. Extremes Start With a Real Value
Use the first value, not 0.
4. Average as double
(double) sum / count, and check count > 0.
There are standard algorithms to identify if an integer is or is not evenly divisible by another integer, identify the individual digits in an integer, determine the frequency with which a specific criterion is met, determine a minimum or maximum value, and compute a sum or average. Each combines iteration with selection: the remainder operator tests divisibility and extracts digits, a counter inside an if measures frequency, a best-so-far variable tracks an extreme, and accumulators for a sum and a count produce an average computed in double.