Math for algorithms: logs, sums, modular arithmetic
Use logarithms, series, modular arithmetic and basic counting in algorithm analysis.
By Invicly Tech, , in Data Structures & Algorithms. About 10 minutes to read.
In short
A small amount of math explains most algorithm costs. Logarithms count halvings, arithmetic and geometric series sum loop work, and modular arithmetic keeps huge numbers manageable. Counting formulas tell you how big a search space is before you try to brute force it.
Explained simply
You only need a small toolbox of math for algorithms. Most of it you already know from school. It just has a few new names.
A logarithm answers: how many times can I cut this in half before I reach 1? Fold a sheet of paper in half again and again. log2 of 1,024 is 10 because you can halve 1,024 ten times. That is why binary search over a billion items needs only about 30 steps.
Sums tell you how much a loop does in total. Adding 1 + 2 + 3 up to n gives about n^2 / 2. Doubling sums like 1 + 2 + 4 + 8 add up to just under twice the last number. These two facts explain most loop costs.
Modular arithmetic means working with remainders, like a clock. After 12 comes 1 again. Programs use it to keep huge numbers small, for hashing and for answers "modulo 10^9 + 7". Counting formulas, like how many ways to arrange or choose items, tell you if trying every option is even possible.
Press Play on a diagram to walk through it one step at a time.
- Logarithms
- log2(10^6) is about 20
- Halving and tree height
- Series
- 1 + 2 + ... + n = n(n+1)/2
- 1 + 2 + 4 + ... + n < 2n
- Modular arithmetic
- (a*b) mod m
- Answers mod 10^9+7
- Counting
- n! permutations
- 2^n subsets
- n choose k
- 113 in binary
1101 = 8 + 4 + 1
- 2Square repeatedly
3^1, 3^2, 3^4, 3^8
- 3Keep the 1-bits
3^8 * 3^4 * 3^1
- 4Multiply
6561 * 81 * 3 = 1,594,323
- 5Cost
About log2(13) squarings, not 12 multiplies
- log2 n is about 3.3
- n^2 = 100
- 2^n = 1,024
- n! = 3,628,800
- log2 n is about 4.3
- n^2 = 400
- 2^n is about a million
- n! is about 2.4 x 10^18
- log2 n is about 5.3
- n^2 = 1,600
- 2^n is about a trillion
- n! is about 8 x 10^47
In depth
Logarithms you should know by heart
log2 n is the number of halvings to get from n down to 1. It is also the number of bits needed to write n in binary, roughly.
The base barely matters in Big-O, because log2 n and log10 n differ only by a constant factor (about 3.32). That is why we just write O(log n).
Useful anchors: log2 of 1,000 is about 10, of a million about 20, of a billion about 30. Two rules cover most algebra: log(a times b) = log a + log b, and log(a^k) = k log a.
- 2^10 = 1,024, about a thousand
- 2^20 is about a million
- 2^30 is about a billion
- log(n!) is about n log n
The two sums behind most loops
Arithmetic series: 1 + 2 + ... + n = n(n+1)/2. A trick: pair the first and last numbers. 1 + n, 2 + (n-1), and so on, each pair adds to n + 1, and there are n/2 pairs. Any loop where the inner part grows by one each round has this shape, so it is O(n^2).
Geometric series: 1 + 2 + 4 + ... + 2^k = 2^(k+1) - 1. The last term is about half the total. So when work doubles each step, the final step dominates. That is why doubling a dynamic array costs only O(n) overall.
- 1 + 2 + ... + n
- = n(n+1)/2
- Inner loop grows by one each round
- Total O(n^2)
- 1 + 2 + 4 + ... + 2^k
- = 2^(k+1) - 1
- Work doubles each step
- Last step is about half the total
Modular arithmetic rules
a mod m is the remainder after dividing a by m. Python writes it a % m, and the result is always between 0 and m - 1 for positive m.
You can take the remainder at every step of addition and multiplication without changing the final answer: (a + b) % m = ((a % m) + (b % m)) % m, and the same for times. This keeps numbers small. Subtraction works too, but in other languages add m before taking the remainder to avoid negatives. Division does not work directly; you need a modular inverse, which for a prime m is pow(b, m - 2, m).
- 117 % 7 = 3
- 225 % 7 = 4
- 33 + 4 = 7
- 47 % 7 = 0
- 5Check
42 % 7 = 0, same answer
Counting how big a search space is
Before brute forcing, count the options. Arranging n distinct items in order gives n! permutations: 10! is about 3.6 million, but 15! is over a trillion. Choosing k items from n, ignoring order, gives n choose k = n! / (k! (n-k)!). Every subset of n items: 2^n, because each item is in or out.
So n = 20 means 2^20, about a million subsets, which is fine. n = 40 means 2^40, a trillion, which is not.
- Permutations of n: n!
- Subsets of n: 2^n
- Choose k of n: n! / (k! (n-k)!)
- math.comb(n, k) and math.perm(n, k) compute these
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Work with logarithms and powers of two~35m
- 2Evaluate arithmetic and geometric series~35m
- 3Compute with modular arithmetic~35m
- 4Count permutations and combinations~35m
- 5Implement fast exponentiation~35m
Key points
- log2 of a billion is about 30, so O(log n) is effectively tiny.
- A geometric series is dominated by its largest term, which is why doubling is cheap overall.
- Fast exponentiation computes a^b mod m in O(log b) multiplications.
- 2^n and n! grow so fast that n around 20 to 25 is the brute-force limit.
Key terms
Tap a card to flip it. 0/4 known
Examples
def power_mod(a, b, m): # O(log b)
result = 1
a %= m
while b > 0:
if b & 1:
result = result * a % m
a = a * a % m
b >>= 1
return result
print(power_mod(2, 100, 10**9 + 7), pow(2, 100, 10**9 + 7))Python's built-in pow(a, b, m) does the same thing.
Last digit of a huge power
What is the last digit of 7^222? The last digit is the number mod 10. Powers of 7 mod 10 go 7, 9, 3, 1, then repeat every 4. Since 222 mod 4 = 2, the answer is the second in the cycle: 9. Python's pow(7, 222, 10) uses fast exponentiation and confirms it without ever building the full 188-digit number.
cycle = [pow(7, k, 10) for k in range(1, 5)]
print(cycle) # [7, 9, 3, 1]
print(pow(7, 222, 10)) # 9
print(len(str(7**222))) # 188Is brute force possible? Counting first
You have 25 numbers and want a subset that sums to a target. There are 2^25, about 33 million subsets. Each needs up to 25 additions, so close to a billion steps, too slow for Python. With 15 numbers it is only 32,768 subsets, instantly fine. Counting first saves you from writing code that will never finish.
import math
for n in (15, 25, 40):
print(n, 2 ** n, math.comb(n, n // 2))
# 15 32768 6435
# 25 33554432 5200300
# 40 1099511627776 137846528820Quick reference
- log2(1e3) is about 10, log2(1e6) about 20, log2(1e9) about 30
- 1 + 2 + ... + n = n(n+1)/2
- 1 + 2 + 4 + ... + 2^k = 2^(k+1) - 1
- (a * b) % m = ((a % m) * (b % m)) % m
- pow(a, b, m) computes a^b mod m in O(log b)
- Subsets: 2^n; permutations: n!; choose: math.comb(n, k)
- 10^9 + 7 is a common prime modulus in problems
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write sum_to(n) that returns 1 + 2 + ... + n in O(1) using the formula, and check it against a loop for n = 100. Expected: 5050.
- Exercise 2medium
Write fast_pow(a, b, m) that returns a^b mod m without using pow's third argument. Example: fast_pow(2, 10, 1000) returns 24.
- Exercise 3hard
Write n_choose_k_mod(n, k) that returns n choose k modulo the prime 10^9 + 7, for n up to 10^6. Example: n_choose_k_mod(5, 2) returns 10, and n_choose_k_mod(1000, 500) matches math.comb(1000, 500) % (10^9 + 7).
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why do problems ask for answers modulo 10^9 + 7?
- The true answer would have thousands of digits. Taking it modulo a large prime keeps numbers inside 64 bits in most languages, and being prime makes modular division possible.
- Does the base of the logarithm matter in Big-O?
- No. Changing the base only multiplies by a constant, which Big-O ignores. Inside an exponent, like n^(log2 3), the base does matter.
- Do I need calculus for algorithms?
- Almost never for everyday problems. Logs, sums, remainders and counting cover the vast majority of what you will meet.