AP Computer Science A · Study guide

Numeric Selection and Iteration Algorithms

AP® Computer Science A · Selection and Iteration

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.

Big Picture

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.

Figure 1. An integer n is evenly divisible by d exactly when n % d == 0.
AlgorithmKey ideaCore code
DivisibilityRemainder is zeroif (n % d == 0)
Individual digitsLast digit, then remove itd = n % 10; n /= 10;
FrequencyCounter increases when a criterion holdsif (test) { count++; }
Maximum / minimumKeep the best so far; replace when beatenif (v > max) { max = v; }
Sum / averageAccumulate; divide as doublesum += v; ... (double) sum / count
Worked Example 1 Divisibility

Counting Divisors and Testing for Prime

Count the divisors of 36, then decide whether 37 is prime (exactly two divisors).

Code
public static int countDivisors(int n)
{
    int count = 0;
    for (int d = 1; d <= n; d++)
    {
        if (n % d == 0)
        {
            count++;
        }
    }
    return count;
}
Output
9
true
false
  1. 1The test. n % d == 0 is true exactly when d divides n evenly.
  2. 236. Divisors 1, 2, 3, 4, 6, 9, 12, 18, 36: nine of them.
  3. 337. Only 1 and 37 divide it, so the count is 2 and 37 is prime.
  4. 439. 3 × 13 = 39, so it has four divisors: not prime.
Result: The output is 9, true, false. Checking 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.

Figure 2. n % 10 gives the last digit of a non-negative integer and n / 10 removes it, so a loop can visit every digit.
Worked Example 2 Digits

Sum and Count of the Digits

Find the sum of the digits of 4719 and how many digits it has.

Code
int n = 4719;
int sum = 0;
int digits = 0;
while (n > 0)
{
    sum += n % 10;
    n /= 10;
    digits++;
}
System.out.println(sum + " " + digits);
Output
21 4
  1. 1Each pass adds the last digit (n % 10) and then removes it (n /= 10).
  2. 2Digits visited: 9, 1, 7, 4, so the sum is 21 and there are 4 passes.
  3. 3Stopping. After the fourth pass n is 0, and 0 > 0 is false.
Result: The output is 21 4. The pair % 10 and / 10 identifies the individual digits in an integer, from right to left.
Passn beforen % 10reversedn after
1471990 × 10 + 9 = 9471
247119 × 10 + 1 = 9147
347791 × 10 + 7 = 9174
444917 × 10 + 4 = 91740
Worked Example 3 Digits

Reversing a Number

Build the number with the digits of 4719 in reverse order.

Code
int n = 4719;
int reversed = 0;
while (n > 0)
{
    int digit = n % 10;
    reversed = reversed * 10 + digit;
    n /= 10;
}
System.out.println(reversed);
Output
9174
  1. 1Shift and add. Multiplying reversed by 10 makes room for the next digit on the right.
  2. 2Trace: 0 → 9 → 91 → 917 → 9174.
Result: The output is 9174. Digits removed from the right of one number can be appended to the right of another, which reverses their order.
Common Mistake 1 · Using n >= 0 in a Digit Loop

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.

Worked Example 4 Frequency

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.

Code
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);
Output
14 6
  1. 1The pattern. A counter starts at 0, a loop visits every candidate, and an if adds 1 only when the criterion holds.
  2. 2Multiples of 7. 7, 14, …, 98: 14 values.
  3. 3Digit sum 5. For two-digit values, k / 10 is the tens digit and k % 10 the ones digit: 5, 14, 23, 32, 41, 50, six values.
Result: The output is 14 6. Counting with a condition determines the frequency with which a specific criterion is met.
Common Mistake 2 · Resetting the Counter Inside the Loop

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.

Figure 3. To find a maximum, keep the largest value seen so far and replace it whenever a larger value appears. Gold bars are the values that set a new maximum.
Worked Example 5 Maximum and minimum

The Largest and Smallest Digit

Find the largest and smallest digit of 4719.

Code
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);
Output
9 1
  1. 1Start with an actual value. Both trackers begin as the first digit, 9, which is guaranteed to be a real candidate.
  2. 2Compare each remaining digit: 1 lowers the minimum; 7 and 4 change nothing.
  3. 3Two separate if statements, because a single value could in principle update both.
Result: The output is 9 1. To find a maximum or minimum, initialize the tracker with the first value, then replace it whenever a larger (or smaller) value appears.
Worked Example 6 Minimum with position

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.

Code
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);
Output
min 4 at x = 4
  1. 1Initialize with the first case, x = 0, whose value is 20.
  2. 2Values for x = 1 to 10: 13, 8, 5, 4, 5, 8, 13, 20, 29, 40.
  3. 3Track both. When a new minimum is found, record its value and its x together.
Result: The output is min 4 at x = 4. A minimum or maximum algorithm can record where the extreme occurred as well as its value.
Common Mistake 3 · Starting a Maximum at Zero

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.

Figure 4. An average needs a sum and a count. Dividing two int values truncates, so cast to double first.
Worked Example 7 Sum and average

An Average That Keeps Its Fraction

Find the sum and average of the whole numbers from 1 to 4.

Code
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);
Output
10
2
2.5
  1. 1Two accumulators. sum adds each value; count adds 1 per value.
  2. 2Integer division. 10 / 4 is 2, losing the fraction.
  3. 3Cast first. (double) sum / count converts sum before dividing: 2.5.
Result: The output is 10, 2, and 2.5. Computing an average needs a sum and a count, and a cast to double before the division.
MistakeEffectFix
Initializing a maximum to 0Wrong when every value is negativeStart with the first value (or Integer.MIN_VALUE)
Using else if for max and min togetherA value that should update both updates only oneUse two separate if statements
Dividing int sum by int countAverage loses its fraction(double) sum / count
Digit loop with n >= 0Infinite loop: 0 / 10 is still 0Use 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.

Common Mistake 4 · Using else if Where Two Updates Are Independent

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.

Core Synthesis

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.