Logarithms
easy 14 minA logarithm answers "what power do I raise the base to?" In code, log2 n is how many times you can halve n before reaching 1, which is why binary search, balanced trees and divide and conquer all run in O(log n) and barely slow down as data grows.
Video lesson · Chapter 1 of 6
Find the first bad signal
Logarithms
1:24Reel
Read caption
Ari follows a knockout winner through 32 entries, then relates five rounds to the height of a perfect binary tree. Double the leaves, add one level.
How it works
Step through the idea, or press Play.
Ask the power question. log2 64 asks: 2 to what power is 64? The answer is 6, because 2^6 = 64
Understand it
Start here
What a logarithm is
A logarithm is the inverse of an exponent. Exponents ask "what do I get if I multiply 2 by itself 6 times?" (). Logarithms ask the reverse: "how many 2s do I multiply to get 64?" (). In computer science the base is almost always 2, because computers work in binary and algorithms split things in half.
The definition
Exponents and logs undo each other
Base
What you multiply by. Base 2 in CS, base 10 for digits, base in maths.
Number
The value you want to reach, such as the size of an array.
Answer
How many times you multiplied, or how many times you can divide back down to 1.
The programmer's view
Count the halvings
Forget the formula for a moment. For a programmer, means: how many times can you divide $n$ by 2 until you reach 1? Halving 64 gives 32, 16, 8, 4, 2, 1. That is 6 divisions, so .
The halving loop
def count_halvings(n): count = 0 while n > 1: n //= 2 count += 1 return countprint(count_halvings(64)) # 6, since 2**6 == 64print(count_halvings(1000)) # 9, log2(1000) is about 9.97Memorise
Powers of two worth knowing
| 2 | 1 | 128 | 7 |
|---|---|---|---|
| 4 | 2 | 256 | 8 |
| 8 | 3 | 512 | 9 |
| 16 | 4 | 1,024 | 10 |
| 32 | 5 | about 1 million | about 20 |
| 64 | 6 | about 1 billion | about 30 |
The shortcut behind the big ones
The rules
Logarithm rules you will use
Product and quotient rules
Power rule
| Rule | Formula | Example |
|---|---|---|
| Identity | , | ; any base, |
| Inverse | ||
| Product | ||
| Power | ||
| Change of base |
Big-O
Change of base: why the base does not matter
Change of base
Since is just a constant, , and are the same curve scaled up or down. Big-O ignores constant factors, so all of them are simply . That is why complexity tables never write the base.
Every base is the same class
In code
Logarithms in Python
import mathn = 64print(math.log2(n)) # 6.0, base 2, the usual one in CSprint(math.log10(n)) # 1.806..., base 10print(math.log(n)) # 4.158..., natural log, base eprint(math.log(n, 3)) # 3.785..., any base: log3(64)# exact integer answers, no floating pointprint(n.bit_length() - 1) # 6 = floor(log2 64)print((1000).bit_length() - 1) # 9 = floor(log2 1000)| Call | Meaning | Use it for |
|---|---|---|
math.log2(n) | as a float | Estimating steps, tree heights |
math.log10(n) | as a float | Rough digit counts |
math.log(n, b) | via change of base | Any other base |
n.bit_length() - 1 | , exact | Integer answers, huge numbers |
Math.log2 in JavaScript, 31 - __builtin_clz(n) in C++, Integer.numberOfTrailingZeros(Integer.highestOneBit(n)) in Java.Why it matters
The power of O(log n)
| linear | Speedup | ||
|---|---|---|---|
| 1,000 | 1,000 | 10 | 100× |
| 1,000,000 | 1,000,000 | 20 | 50,000× |
| 1,000,000,000 | 1 billion | 30 | 33 million× |
Why it grows so slowly
- 11 thousand itemsabout 10 comparisons
- 21 million itemsabout 20 comparisons
- 31 billion itemsabout 30 comparisons
Each box is a thousand times more data and only ten more steps.
Classic example
Binary search
One step of binary search
Counting the steps
Database queries
B-tree indexes narrow down to the right disk page in a handful of reads.
Git bisect
Finds the commit that introduced a bug among commits in about test runs.
Standard libraries
Python's
bisect, C++'sstd::binary_search, Java'sArrays.binarySearch.
Trees
Tree height is log n
Each level doubles
From node count to height
| Nodes | Height (edges) | Levels |
|---|---|---|
| 15 | 3 | 4 |
| 1,024 | 10 | 11 |
| about 1 million | about 20 | about 20 |
| about 1 billion | about 30 | about 30 |
BST
O(log n) search, insert and delete when balanced; O(n) if it degrades to a chain.
AVL and red-black trees
Rebalance on every change so the height stays O(log n).
B-tree
Hundreds of children per node, so height is : a few disk reads for billions of rows.
Heap
A complete tree: push and pop move one value up or down levels.
Pattern spotting
Recognising O(log n)
Is this logarithmic?
Patterns that signal log n
Halving
The problem size is cut in half, or by any constant factor, every step.
Binary search
Sorted data, or a yes/no answer that flips once, searched by eliminating half.
Tree traversal
Walking from root to leaf in a balanced tree or heap.
Divide and conquer
Splitting into equal parts gives levels of recursion.
Must-know O(log n) algorithms
Binary search
Search a sorted array.
BST operations
Insert, search and delete in a balanced tree.
Fast exponentiation
Compute by squaring, multiplications.
Fenwick tree
Prefix sums with updates in .
Segment tree
Range queries and updates on arrays.
Heap operations
Insert and extract the minimum or maximum.
Logarithmic
n //= 2orn //= 10inside a loop.i *= 2untilireachesn.- Recursing on one half and ignoring the other.
- Following one path down a balanced tree.
Not logarithmic
n -= 2ori += 100: still O(n).- Recursing on both halves and touching every item: O(n log n).
- Binary search on unsorted data: wrong answers, not faster ones.
- Walking down an unbalanced tree: up to O(n).
Recap
Key takeaways
Key points
- means : a log asks which power gives the number.
- For programmers, is how many times you can halve before reaching 1.
- Any algorithm that divides its input by a constant each step is O(log n); doubling adds one step.
- Know the anchors: , , .
- A balanced binary tree with nodes has height , so tree operations are O(log n).
- Bases differ only by a constant factor, so Big-O just writes O(log n).
- Use
bit_lengthor integer loops when you need an exact integer log.