Sums, Logarithms and Factorials
Analyzing algorithms needs only a small amount of mathematics, but it needs it constantly. This lesson collects the facts used throughout the course, explains where each one comes from, and shows how to use them. It can be read on its own or consulted when a lesson refers to it.
The Complexity Analysis lesson gives the most common summation formulas in a table; here we justify them and add a few more.
- How to manipulate summation notation and derive the closed forms of arithmetic and geometric series.
- Why harmonic numbers appear in algorithm analysis and how to bound sums with integrals.
- The essential logarithm identities, floors and ceilings, and why the base matters inside an exponent.
- How fast factorials grow via Stirling's approximation and why .
Summation notation
The expression
is read "the sum of for from 1 to ". The variable is a dummy: and are the same number. Three rules are used all the time:
- Constants come out: .
- Sums split: .
- Indices shift: , and summing in reverse order changes nothing: .
A loop is a sum: the number of times the body of for (int i = 1; i <= n; i++) runs is . Nested loops become nested sums, which is how the complexity of loops is calculated.
Arithmetic series
Why. Write the sum twice, once forwards and once backwards, and add the columns:
S = 1 + 2 + ... + (n-1) + n
S = n + (n-1) + ... + 2 + 1
2S = (n+1) + (n+1) + ... + (n+1) + (n+1) = n (n+1)
Each of the columns adds up to , so . (The story goes that Gauss found this trick as a schoolboy.)
Where it appears. In every triangular loop, where the inner loop runs times (or ): bubble sort, selection sort and insertion sort in its worst case all perform about comparisons. It is : half of the square, but still quadratic.
More generally, any sum of terms that grow linearly is quadratic: .
Sums of powers
For example, . These formulas are proved by induction (see the next lesson). For analysis we usually only need their order:
Why. Each of the terms is at most , so the sum is at most . And the largest half of the terms (those with ) are each at least , so the sum is at least . Both bounds are a constant times . This "upper bound by the largest term, lower bound by half of the terms" argument works for many sums.
Geometric series
Why. Call the sum . Then . Subtracting, almost every term cancels: .
The important part is what happens for large , which depends only on the ratio :
| Ratio | Behavior | Order of the sum | Example |
|---|---|---|---|
| Each term is larger than all the previous ones together (for ); the last term dominates | |||
| All terms equal | |||
| The terms shrink; the first term dominates, and the sum never exceeds |
This table is the heart of the analysis of divide and conquer. In the recursion tree of a division scheme, the work per level forms a geometric series of ratio , and the three cases of the formula are exactly the three rows above: the work is concentrated at the bottom, spread evenly, or concentrated at the top.
It also explains a fact that surprises many students: a for loop that doubles its variable (for (i = 1; i < n; i *= 2)) with a body of cost costs only , which is , not . The same argument explains why adding elements to an ArrayList costs in total: whenever the internal array is full, it is replaced by one larger by a constant factor (50% larger in Java) and the elements are copied, but the sizes of those copies form a geometric series, so all the copies together cost only a constant times the final size.
Harmonic numbers
The harmonic series grows, but very slowly: , , . The approximation (where is the Euler-Mascheroni constant) is accurate to two decimals from on.
Where it appears. Whenever the probability of an event is at step . The average number of comparisons of Quicksort with random pivots is about , and that comes from a harmonic number. It also appears in the number of times a running maximum changes when scanning a random array (about times).
Bounding sums with integrals
When is increasing, each term lies between the area under from to and the area from to . Adding up,
(with the inequalities reversed for decreasing ). For example, , which is why . And , which agrees with .
Logarithms
The logarithm is the inverse of the exponential:
In algorithmics, answers a very concrete question: how many times can be halved before reaching 1? That is why it appears in every algorithm that discards half of the data at each step. Binary search on sorted elements makes at most comparisons: 10 for , 20 for , 30 for .
Rules
| Rule | Formula | Use |
|---|---|---|
| Product | ||
| Quotient | Levels of a recursion tree: | |
| Power | , so | |
| Change of base | All logarithms differ by a constant factor | |
| Swap | Number of leaves of a recursion tree: | |
| Inverse |
The change of base rule has an important consequence: . Since constant factors are ignored in asymptotic notation, the base of the logarithm does not matter inside , and we simply write . The base does matter inside an exponent: and are very different.
Logarithms grow slowly
For every constant , : the logarithm grows more slowly than any power of , even or (although for the difference only shows for astronomically large ). Likewise, any power of a logarithm, , grows more slowly than . This justifies the ordering used in the growth rates lesson.
Floors and ceilings
(floor) is the largest integer not greater than , and (ceiling) the smallest integer not less than . They appear when sizes are divided: an array of elements is split into halves of and elements. In asymptotic analysis they can almost always be ignored: assuming is a power of 2 does not change the order of the result for the usual algorithms. Two exact facts worth remembering:
- The number of bits needed to write in binary is .
- The height of a complete binary tree (such as a heap) with nodes is .
Factorials and Stirling's formula
is the number of permutations of elements, so it measures exhaustive search over orderings: task assignment, the traveling salesman, and the number of possible orders a sorting algorithm must distinguish.
Stirling's formula gives its size:
It is surprisingly accurate: the relative error is about 1.7% for , 0.8% for and 0.4% for . Two consequences:
- grows faster than any exponential , because has a base that itself grows. And , so .
- . Taking logarithms in Stirling's formula, . For : , while .
The second fact is the core of the lower bound for comparison sorting: an algorithm that only compares elements must distinguish among possible orders, and each comparison has two outcomes, so it needs at least comparisons in the worst case.
A simpler argument gives the same order without Stirling: the largest half of the factors of are all at least , so and , which is ; and gives .
Self-check
1. Triangular loop. How many times does the body of for (i = 0; i < n; i++) for (j = i + 1; j < n; j++) run?
For each , the inner loop runs times. The total is , which is . It is the number of pairs of different elements.
2. Doubling. A loop doubles i from 1 while i is less than n, and its body costs i operations. What is its total cost?
up to less than : a geometric series of ratio 2, dominated by its last term, which is less than . The total is less than : .
3. Base of the logarithm. Is ? Is ?
The first, yes: the two logarithms differ by a constant factor (3.32). The second, no: , while . A constant factor inside an exponent changes the order.
4. Halving. A recursive algorithm halves the problem until it has size 1. How many levels does the recursion have for ?
About levels (19.93, so 20 halvings with integer division).
5. Factorial. Order these functions from slowest to fastest growth: , , , , .
, , , , .
- Off-by-one errors in the limits of a sum. and have the same number of terms but different values.
- Changing the base of a logarithm inside an exponent. , not .
- Confusing with . .
Key ideas
- Arithmetic series: ; in general .
- Geometric series: dominated by the last term if , by the first if ; all terms count equally if . This is the key to divide and conquer.
- Harmonic numbers: ; they appear in the average case of randomized algorithms such as Quicksort.
- Logarithms: counts halvings; the base does not matter inside , but it does inside an exponent.
- Factorials: grows faster than any exponential, and .
Errors, suggestions and public questions open a form on GitHub, visible to everyone.