Math for Algorithms
How logarithms, powers of two, the sum 1 + 2 + ... + n, pair counts and modulo explain running times, and what interviewers ask about them.
On this page
- Logarithms count halvings
- Powers of two count subsets and doublings
- The sum 1 + 2 + ... + n
- Counting pairs and orderings
- Modulo and wrap-around
- Code for halvings, the sum and wrap-around
- Variants and where the formulas stop applying
- Pitfalls with modulo, division and large numbers
- In the interview
- What to practise next
A small set of math facts explains the running time of most algorithms: logarithms count how many times a problem can be halved, powers of two count the subsets of a set, the sum 1 + 2 + ... + n is the cost of a loop whose passes keep getting longer, n(n - 1) / 2 counts pairs, and the remainder operator (modulo) handles wrap-around and very large answers. Knowing these lets you estimate an algorithm's cost before you write it, and turn some loops into a single formula.
Without them, the O(log n), O(2ⁿ) and O(n²) in a complexity analysis are labels you have to memorise. With them, you can see why binary search is fast, why trying every subset is slow, and why a nested loop that checks every pair is quadratic.
Logarithms count halvings
The logarithm base 2 of n, written log₂ n, is the number of times you can halve n before reaching 1. Starting from 64 you can halve 6 times (64, 32, 16, 8, 4, 2, 1), so log₂ 64 = 6. Equivalently, log₂ n is the power of 2 that gives n: 2⁶ = 64.
When n is not a power of 2, integer halving rounds down at each step. The trace below halves 100 until it reaches 1.
steps = 0while n > 1: n = floor(n / 2) steps = steps + 1return steps- sizes0100
- n
- 100
- steps
- 0
1The trace starts with n = 100.
- sizes0100150
- n
- 50
- steps
- 1
2100 is more than 1, so halve it: 50.
- sizes0100150225
- n
- 25
- steps
- 2
3Half of 50 is 25.
- sizes0100150225312
- n
- 12
- steps
- 3
4Half of 25 is 12.5, rounded down to 12. The rounding barely affects the count.
- sizes010015022531246
- n
- 6
- steps
- 4
5Half of 12 is 6.
- sizes01001502253124653
- n
- 3
- steps
- 5
6Half of 6 is 3.
- sizes0100150225312465361
- n
- 1
- steps
- 6
7Half of 3 is 1.5, rounded down to 1.
- sizes0100150225312465361
- n
- 1
- steps
- 6
8n is 1, so the loop stops after 6 halvings. log₂ 100 is about 6.64, rounded down to 6.
Logarithms grow very slowly. Halving the work at every step, as binary search does, means that a million items need about 20 steps and a billion items need about 30. This works because 2¹⁰ = 1,024 is close to a thousand, so every factor of 1,000 in the input size adds about 10 halvings.
| n | log₂ n, about |
|---|---|
| 1,000 | 10 |
| 1,000,000 | 20 |
| 1,000,000,000 | 30 |
The base of the logarithm does not matter in Big-O. log₂ n is about 3.32 times log₁₀ n, which is a constant factor, so both are written O(log n).
Powers of two count subsets and doublings
Doubling grows as fast as halving shrinks. If each of n items can be either included or left out, there are 2 choices per item and 2ⁿ combinations in total. Three items give 2³ = 8 subsets, including the empty one, and 30 items give more than a billion. Trying every subset therefore only works for about 20 to 25 items.
Powers of two also appear when a structure doubles in size. The sizes 1, 2, 4, ..., 2ᵏ add up to 2ᵏ⁺¹ - 1, which is just under twice the largest term. For example, 1 + 2 + 4 + 8 + 16 + 32 = 63.
The sum 1 + 2 + ... + n
This sum appears whenever an inner loop gets one step longer (or one step shorter) on each pass of the outer loop. To add it up, write the numbers twice, once forward and once backward, and pair them. Each pair adds up to n + 1, and there are n pairs.
Those n pairs add up to n(n + 1), which counts every number twice, so
1 + 2 + ... + n = n(n + 1) / 2. For n = 100 this is 100 × 101 / 2 = 5,050.
For complexity analysis only the shape matters: the sum grows like n²/2, so an inner loop that runs 1, 2, 3, ... up to n times is O(n²).
Counting pairs and orderings
The number of ways to choose 2 items out of n is n(n - 1) / 2. Each of the n items pairs with the other n - 1, which counts every pair twice, so the product is divided by 2. For 64 items this gives 64 × 63 / 2 = 2,016 pairs. This is the count behind the pair loop in Big-O Notation, and it is why "check every pair" is O(n²).
The number of ways to arrange n items in a row is n! ("n factorial"), which is n × (n - 1) × ... × 1. Three items have 3! = 6 orderings, and 10 items have 10! = 3,628,800. Trying every ordering is therefore limited to about 10 items.
Modulo and wrap-around
The modulo operator, written %, gives the remainder after division. For example, 7 % 6 is 1, because 7 = 1 × 6 + 1. It is used whenever a value has to wrap around:
- Circular positions.
(i + k) % nmoveskplaces around a ring ofnpositions, such as the seats at a round table, the hours on a clock, the weekdays or a circular buffer. Moving 4 places from position 3 in a ring of 6 gives7 % 6, which is position 1. - Even or odd.
x % 2is 0 for even numbers and 1 for odd numbers. - Very large answers. Counting problems often ask for the answer "modulo 1,000,000,007" because the exact value is too large to store. The remainder of a sum or a product depends only on the remainders of its parts, so you can take the remainder after every addition or multiplication and get the same final result.
Code for halvings, the sum and wrap-around
// Halvings until n reaches 1: about log2(n)
function countHalvings(n) {
let steps = 0;
while (n > 1) {
n = Math.floor(n / 2); // JS division gives decimals
steps++;
}
return steps;
}
// 1 + 2 + ... + n, no loop needed
const sumTo = (n) => (n * (n + 1)) / 2;
// Move k seats around a table of n seats; k may be negative
const moveSeat = (i, k, n) => (((i + k) % n) + n) % n;
countHalvings(100); // 6
sumTo(100); // 5050
moveSeat(3, 4, 6); // 1
moveSeat(1, -3, 6); // 4# Halvings until n reaches 1: about log2(n)
def count_halvings(n):
steps = 0
while n > 1:
n //= 2 # whole-number division
steps += 1
return steps
# 1 + 2 + ... + n, no loop needed
def sum_to(n):
return n * (n + 1) // 2
# Move k seats around a table of n seats; k may be negative
def move_seat(i, k, n):
return (i + k) % n # Python's % is never negative here
count_halvings(100) # 6
sum_to(100) # 5050
move_seat(3, 4, 6) # 1
move_seat(1, -3, 6) # 4| Approach | Time | Space | Why |
|---|---|---|---|
| Sum 1..n with a loop | O(n) | O(1) | One addition per number. |
| Sum 1..n with the formula | O(1) | O(1) | Same work whatever n is. |
| Count halvings | O(log n) | O(1) | The loop runs about log₂ n times. |
Variants and where the formulas stop applying
Rounding a logarithm
The halving loop returns the logarithm rounded down. For n = 100 it returns 6, while log₂ 100 is about 6.64. If you need the number of bits in a number or the worst-case number of comparisons in a binary search, the answer is one more than the rounded-down logarithm: a binary search over 100 sorted items needs at most 7 comparisons. In Big-O this difference disappears.
Ordered pairs and unordered pairs
The formula n(n - 1) / 2 counts unordered pairs, where (a, b) and (b, a) are the same pair. If the order matters, as in "pick a first item and a second item", there are n(n - 1) pairs. A nested loop whose inner index starts at i + 1 visits each unordered pair once, while an inner loop that starts at 0 visits every pair twice and also pairs each item with itself.
Modulo arithmetic on large answers
Addition and multiplication can be reduced modulo m at any step. Subtraction needs one extra step, because the difference can be negative: write ((a - b) % m + m) % m in JavaScript. Division does not work with a plain % at all. Dividing under a modulus uses a modular inverse, which is covered when a problem needs it, so before dividing check whether the formula can be rearranged to avoid the division. The modulus 1,000,000,007 is used so often because it is prime and because the product of two values below it, about 10¹⁸, still fits in a 64-bit integer. In JavaScript that product does not fit in a regular number, so use BigInt.
Loops that double, and sums that give n log n
A loop whose variable doubles on every pass, such as for (j = 1; j < n; j *= 2), runs about log₂ n times, because doubling up to n takes as many steps as halving down from n. Put that loop inside a loop that runs n times and the total is O(n log n). Merge sort has the same shape: it halves the array about log₂ n times, and each level of halving does O(n) work in total to merge. A second sum that comes up is 1 + 1/2 + 1/3 + ... + 1/n, which grows like ln n. A loop that visits n/1 items for the first value of i, n/2 items for the second, and so on does about n · ln n work, which is O(n log n) and not O(n²).
When a formula does not apply
The formula n(n + 1) / 2 works only when the loop lengths grow by exactly 1 each pass. If the inner loop doubles its length each pass, the lengths form a sum of powers of two, and if it depends on the data (for example, it stops early), you have to count the work directly. The same applies to halving: the log₂ n count assumes the input is cut in half every step. If a step removes only a constant number of items, the count is n, not log n.
Pitfalls with modulo, division and large numbers
In the interview
Math from this page shows up in two ways. The first is in the constraints of a problem, which tell you how fast the solution must be. A limit of about 10⁵ items rules out O(n²) and points to O(n log n) or O(n). A limit of about 5,000 allows O(n²). A limit of 20 to 25 suggests that trying every subset (2ⁿ) is intended, and a limit of about 10 suggests trying every ordering (n!). The second is in the statement itself: "return the answer modulo 10⁹ + 7" means the count is huge, and "wrap around", "circular" or "every k-th" means modulo.
Questions to expect:
- "Why is binary search O(log n)?" Each comparison discards half of the remaining range, so the number of comparisons is the number of times the size can be halved before reaching 1, which is log₂ n.
- "Does the base of the logarithm matter?" No. Changing the base multiplies the result by a constant (log₂ n is about 3.32 × log₁₀ n), and Big-O ignores constant factors.
- "What is the complexity of a loop where the inner loop runs i times?" The inner body runs 1 + 2 + ... + n = n(n + 1) / 2 times, which is O(n²). The factor of 1/2 is dropped, so it has the same complexity as a full n by n loop, though it does about half the work.
- "Why is appending to a dynamic array O(1) on average if it sometimes copies everything?" The array doubles when it is full, so the copy sizes are 1, 2, 4, ..., n. These add up to less than 2n over n appends, which is less than 2 copies per append.
- "Why is sorting O(n log n) and not O(n²)?" A divide-and-conquer sort such as merge sort halves the array until single items remain, which takes about log₂ n levels. Each level does O(n) work in total to merge, so the total is n × log₂ n.
- "What is the complexity of an inner loop that doubles its variable?" It runs about log₂ n times, so inside an outer loop of
npasses the total is O(n log n). - "Can you compute 1 + 2 + ... + n without a loop?" Yes, use n(n + 1) / 2, which takes O(1) time. In JavaScript, mention that
n * (n + 1)must stay below about 9 × 10¹⁵ to remain exact. - "How do you move backwards in a circular array?" Use
((i - k) % n + n) % n, because the%of a negative number is negative in JavaScript, Java and C++. - "Why does the problem ask for the answer modulo 10⁹ + 7?" The exact count is too large for a 64-bit integer. The modulus is prime and small enough that the product of two remainders still fits in 64 bits, and reducing after every operation gives the same final remainder.
You halve a list of 1,000,000 items again and again until 1 item is left. About how many halvings is that?
An inner loop runs 1 time, then 2 times, then 3 times, up to 100 times. How many times does its body run in total?
Seats are numbered 0 to 4 around a table. In JavaScript, what does (0 - 1) % 5 give?
What to practise next
Try the sum formula on The Missing Exam Paper and modulo on Rabbit Counter Wraparound. Then How to Approach a Problem shows how to use these estimates on problems you have not seen before.