AP Computer Science A · Study guide

Informal Run-Time Analysis

AP® Computer Science A · Selection and Iteration

Informal Run-Time Analysis

Measuring how much work code does by counting how many times its statements execute: counts for single, stepped, halving, and nested loops, how counts grow with input size, and how to compare two correct algorithms.

Big Picture

Two programs can produce the same answer while doing very different amounts of work. A statement execution count indicates the number of times a statement is executed by the program. Statement execution counts are often calculated informally through tracing and analysis of the iterative statements, and they make it possible to predict how running time changes as the input grows and to compare algorithms. A single loop's count grows in step with its input; a nested loop's count grows much faster; a halving loop's count barely grows at all.

1Statement Execution Counts

Statements outside any loop execute once. Statements inside a loop execute once per pass, and statements inside nested loops execute once per pass of the innermost loop. Counting how many times a particular statement runs, usually the one in the innermost body, gives a simple measure of how much work a code segment does, independent of how fast a particular computer is.

Timing a program with a clock is less useful for this purpose, because the same code runs at different speeds on different machines and even from one run to the next. Counts are exact and repeatable, and they can be worked out by reading the code, before it ever runs. That makes them the right tool for comparing designs while a program is still being written.

For a for loop, each part of the header has its own count. The initialization runs once; the Boolean expression runs once per pass plus one final time when it fails; the body and the update run once per pass. Questions usually ask about one specific statement, so identify it first and then count how many passes reach it.

Figure 1. A statement execution count indicates the number of times a statement is executed by the program. In a loop, the check runs one more time than the body.
Part of for (int i = 0; i < n; i++)Executions
Initialization1
Boolean expressionn + 1
Body statementn
Updaten
Worked Example 1 Counting by instrumenting

Let the Program Count for You

Add a counter to measure how many times the body runs, then compare with the prediction n.

Code
int n = 7;
int sum = 0;
int bodyCount = 0;
for (int i = 0; i < n; i++)
{
    sum += i;
    bodyCount++;
}
System.out.println(sum + " " + bodyCount);
Output
21 7
  1. 1Prediction. i takes the values 0 to 6, so the body runs n = 7 times.
  2. 2Measurement. The extra counter confirms 7.
  3. 3Other parts. The check i < n runs 8 times and the update 7 times; the initialization runs once.
Result: The output is 21 7. Adding a counter is a simple way to check a statement execution count found by reasoning.
Common Mistake 1 · Forgetting the Final Check

A loop whose body runs n times evaluates its Boolean expression n + 1 times: once before each pass and once more when it becomes false. If a question asks how many times the condition is evaluated, include that last check.

2Counting Single Loops

For a loop whose control variable goes from a to b inclusive in steps of 1, the body runs b - a + 1 times; with a strict < bound it runs b - a times. For larger steps, the count is roughly the length of the range divided by the step, but off by one surprises are common, so listing the values that pass the check is safer than dividing.

Statements inside an if within a loop run only on the passes where the condition is true. Their counts depend on the data, not just the loop bounds: counting the multiples of 7 from 1 to 100 runs the loop body 100 times but the counter update only 14 times.

Worked Example 2 Steps other than 1

Counting a Loop That Skips

How many times does the body run?

Code
int count = 0;
for (int i = 0; i < 20; i += 3)
{
    count++;
}
System.out.println(count);
Output
7
  1. 1List the values. 0, 3, 6, 9, 12, 15, 18 pass the check; 21 fails.
  2. 2Count them: 7.
Result: The body runs 7 times. For steps larger than 1, listing the values that pass the check is the most reliable way to count.
Common Mistake 2 · Dividing Instead of Listing

for (int i = 0; i < 20; i += 3) runs 7 times, not 20 / 3 ≈ 6.7 or 6. Whether the endpoints count depends on the starting value and the bound. List the values that pass the check whenever the step is not 1.

3Counting Nested Loops

For nested loops whose inner bound does not depend on the outer variable, the inner body runs (outer passes) × (inner passes) times: two loops of n passes each give n² executions. When the inner bound depends on the outer variable, add the inner counts for each outer pass; for inner counts 0, 1, …, n − 1, the total is n(n − 1) / 2.

These two results are the most common nested-loop counts. Both grow roughly with the square of n: the triangle does about half the work of the square, but doubling n still roughly quadruples either one. That rapid growth is why nested loops over large inputs can be slow.

Worked Example 3 Nested counts

Fixed and Dependent Inner Loops

For n = 5, predict how many times each inner statement runs.

Code
int n = 5;
int fixedCount = 0;
int triangleCount = 0;
for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
    {
        fixedCount++;
    }
    for (int j = 0; j < i; j++)
    {
        triangleCount++;
    }
}
System.out.println(fixedCount + " " + triangleCount);
Output
25 10
  1. 1Fixed inner bound. 5 × 5 = 25.
  2. 2Bound j < i. 0 + 1 + 2 + 3 + 4 = 10, which is n(n − 1) / 2.
  3. 3Comparison. The triangle does a little under half the work of the square for the same n.
Result: The output is 25 10. Multiply for fixed bounds; add the inner counts for bounds that depend on the outer variable.
Worked Example 4 Counting by hand

A Triangle Counted Without Running It

How many times does the println run? Work it out before running the code.

Code
int lines = 0;
for (int i = 1; i <= 4; i++)
{
    for (int j = i; j <= 4; j++)
    {
        System.out.println(i + "-" + j);
        lines++;
    }
}
System.out.println(lines + " lines");
Output
1-1
1-2
1-3
1-4
2-2
2-3
2-4
3-3
3-4
4-4
10 lines
  1. 1Inner counts. For i = 1, j runs 1 to 4: 4 times. For i = 2: 3 times. For 3: 2. For 4: 1.
  2. 2Add them: 4 + 3 + 2 + 1 = 10.
Result: The println inside runs 10 times, matching the count computed by hand. Tracing the inner count for each outer value and adding gives statement counts without running anything.

4Counting Halving Loops

A loop that divides its control variable by 2 each pass, as in while (n > 1) { n = n / 2; }, needs only as many passes as it takes to halve n down to 1. Starting from 1000 that is 9 passes; from 2000, 10; from a million, about 20. Doubling the starting value adds just one pass.

This slow growth is why repeatedly cutting a problem in half is such a powerful idea in computing. A process that eliminates half of the remaining possibilities each step, such as guessing a number between 1 and 1000 with "higher" or "lower" hints, finishes in a handful of steps even for very large ranges.

Figure 2. A loop that halves its variable each pass needs only a few passes even for large starting values.
Worked Example 5 Halving loops

How Many Halvings From 1000?

Count the passes for starting values 1000 and 2000.

Code
public static int halvings(int n)
{
    int passes = 0;
    while (n > 1)
    {
        n = n / 2;
        passes++;
    }
    return passes;
}
Output
9
10
19
  1. 11000: 500, 250, 125, 62, 31, 15, 7, 3, 1: 9 passes.
  2. 22000: one extra halving reaches 1000, so 10.
  3. 31,000,000: only 19 passes.
Result: The output is 9, 10, 19. When each pass halves the remaining value, doubling the input adds just one pass.

5How Counts Grow

Informal analysis is most useful for predicting what happens as inputs get larger. Compare the counts for a few sizes, such as n = 10, 20, 40, 80. A single loop's count doubles each time n doubles. A nested loop's count quadruples. A halving loop's count increases by one. These patterns hold no matter how fast the computer is.

For small inputs, any reasonable algorithm is fast enough. The differences matter when inputs grow to thousands or millions of values: a single loop over a million values does a million steps, while a nested loop over them would do a trillion. Recognizing the shape of the loops in a program, and therefore how its count grows, is the core of informal run-time analysis.

Figure 3. Statement counts reveal how work grows. Doubling n doubles a single loop's count, adds about one pass to a halving loop, and quadruples a nested loop's count.
Loop shapeInner statement countExample
Single loop, step 1, n valuesnfor (i = 0; i < n; i++)
Single loop, step kabout n / kfor (i = 0; i < 20; i += 3): 7
Halving loopnumber of halvings (small)1000 → 1: 9 passes
Nested, fixed boundsn × m5 × 5 = 25
Nested, inner bound depends on outersum of inner counts0 + 1 + 2 + 3 + 4 = 10
nSingle loop (n)Nested (n × n)Halving from n
10101003
20204004
40401,6005
80806,4006
Common Mistake 3 · Judging Efficiency From One Small Input

Two algorithms may take about the same time for n = 5 and wildly different times for n = 5,000. Compare how their counts grow as n doubles, not just a single count at one small size.

6Comparing Algorithms

When two algorithms solve the same problem correctly, statement execution counts show which does less work. Counting divisors by testing every value from 1 to n takes n passes; testing only up to n / 2 and counting n itself separately takes about half as many, with the same result. Small insights about the problem often translate directly into fewer passes.

Efficiency never excuses an incorrect result, so check correctness first: the faster version must produce exactly the same answers, including at edge cases such as n = 1. Then compare counts, either by reasoning about the loops or by adding counters to both versions and running them on the same inputs.

Figure 4. Two correct algorithms can do very different amounts of work. Comparing their statement execution counts shows which is more efficient.
Worked Example 6 Comparing algorithms

Two Ways to Count Divisors

Both methods count the divisors of 100. Compare their answers and their loop passes.

Code
public static void versionA(int n)
{
    int divisors = 0;
    int passes = 0;
    for (int d = 1; d <= n; d++)
    {
        passes++;
        if (n % d == 0)
        {
            divisors++;
        }
    }
    System.out.println("A: " + divisors + " divisors, " + passes + " passes");
}

public static void versionB(int n)
{
    int divisors = 1;
    int passes = 0;
    for (int d = 1; d <= n / 2; d++)
    {
        passes++;
        if (n % d == 0)
        {
            divisors++;
        }
    }
    System.out.println("B: " + divisors + " divisors, " + passes + " passes");
}
Output
A: 9 divisors, 100 passes
B: 9 divisors, 50 passes
  1. 1Version A tests every candidate from 1 to n: 100 passes.
  2. 2Version B starts its count at 1 for n itself and tests only up to n / 2, because no other divisor can be larger: 50 passes.
  3. 3Same answer. Both find 9 divisors; B does half the work.
Result: The output shows 9 divisors from both, with 100 and 50 passes. Comparing statement execution counts is the informal way to decide which correct algorithm is more efficient.
Worked Example 7 A loop versus a formula

Adding 1 Through n Two Ways

Both approaches compute 1 + 2 + … + 100. Compare the number of additions each performs.

Code
int n = 100;
int total = 0;
int additions = 0;
for (int k = 1; k <= n; k++)
{
    total += k;
    additions++;
}
int formula = n * (n + 1) / 2;
System.out.println(total + " after " + additions + " additions");
System.out.println(formula + " from one calculation");
Output
5050 after 100 additions
5050 from one calculation
  1. 1The loop performs one addition per value: n = 100 of them.
  2. 2The formula n(n + 1) / 2 uses a fixed handful of operations whatever n is.
  3. 3Growth. For n = 1,000,000, the loop would do a million additions; the formula still does a few operations.
Result: Both print 5050. When a mathematical insight replaces a loop, the work stops depending on the size of the input at all.
Common Mistake 4 · Optimizing Before Checking Correctness

A version that does half the work but gives the wrong answer for some inputs is not an improvement. In the divisor example, check n = 1: n / 2 is 0, so the loop makes no passes, and the count that started at 1 for n itself correctly reports one divisor. A faster version that forgot to count n itself would report too few for every input. Always confirm the edge cases.

Four Habits for Counting Work

1. Pick the Statement

Count the innermost statement the question names.

2. List When Unsure

Write the values that pass the check, then count them.

3. Multiply or Add

Fixed nested bounds multiply; dependent bounds add.

4. Watch the Growth

Double n: single ×2, nested ×4, halving +1.

Core Synthesis

A statement execution count indicates the number of times a statement is executed by the program. Statement execution counts are often calculated informally through tracing and analysis of the iterative statements. A loop body with n passes contributes n executions and its Boolean expression n + 1; nested loops multiply their pass counts when the bounds are fixed and add the inner counts when the inner bound depends on the outer variable; a loop that halves its variable needs only a few passes. Comparing counts, and how they grow as the input grows, allows algorithms to be compared informally.