3.2Counting Steps: The Summation Algorithm
Covers IGNOU MCS-211 §3.4, 3.4.1
Before simplifying to big-O, it helps to count steps exactly at least once. This page counts every unit of work in a small summation algorithm, checks the count with a program, and then states the general rules for simplifying.
The algorithm
Compute :
SumOfCubes(n)
1 declare total, i
2 total ← 0
3 for i ← 1 to n do
4 total ← total + i * i * i
5 return totalThe cost model
Each basic operation costs 1 unit:
| Line | Work | Units |
|---|---|---|
| 1 | Declaration (no run-time work) | 0 |
| 2 | One assignment | 1 |
| 3 | Initialise i (1) + test i ≤ n ( times, the last test fails) + increment i ( times) | |
| 4 | 2 multiplications + 1 addition + 1 assignment, times | |
| 5 | Return | 1 |
| Total |
#include <stdio.h>
/* Sum of cubes 1^3 + ... + n^3, counting "units" the way the
step-count model does: assignment 1, each loop test 1,
each increment 1, body 4 (2 mult + 1 add + 1 assign), return 1. */
long long sum_of_cubes(int n, long *units)
{
long long total;
int i;
*units = 0;
total = 0; *units += 1; /* line 2 */
i = 1; *units += 1; /* loop: initialise */
while (1) {
*units += 1; /* loop: test i<=n */
if (!(i <= n))
break;
total = total + (long long)i * i * i; /* line 4 */
*units += 4;
i++; *units += 1; /* loop: increment */
}
*units += 1; /* return */
return total;
}
int main(void)
{
int sizes[] = {1, 10, 100};
for (int t = 0; t < 3; t++) {
long units;
int n = sizes[t];
long long s = sum_of_cubes(n, &units);
printf("n = %3d: sum = %10lld, units = %4ld, 6n + 4 = %4d\n", n, s, units, 6 * n + 4);
}
return 0;
}n = 1: sum = 1, units = 10, 6n + 4 = 10
n = 10: sum = 3025, units = 64, 6n + 4 = 64
n = 100: sum = 25502500, units = 604, 6n + 4 = 604The sums agree with the formula from Unit 2: for , .
From the count to the order
The general rules used in this unit:
- Report the worst-case running time unless told otherwise.
- Keep only the fastest-growing term (drop lower-order terms).
- Drop constant factors.
So becomes . A different cost model (for example, charging 2 units for a multiplication) changes the constants — perhaps — but never the order . This is why big-O is the right level of detail: it does not depend on such choices.
Key takeaways
- Line-by-line counting gives an exact , e.g. for the sum of cubes.
- A loop of iterations has tests and increments.
- Drop lower-order terms and constants: .
- The order of growth does not depend on the exact unit costs.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Count the units of p ← 1; for i ← 1 to n do p ← p * 2; return p (assignment, test, increment, multiplication and return cost 1 unit each) and give the order.
Show worked answer
p ← 1: 1. Loop control: initialise 1 + tests (n + 1) + increments n = 2n + 2. Body: 1 multiplication + 1 assignment = 2 units, n times = 2n. Return: 1. Total T(n) = 1 + 2n + 2 + 2n + 1 = 4n + 4 = Θ(n).