What log n really means
log₂ n is how many times you can halve n before reaching 1. That's why on a million items takes about 20 steps.
The idea
log₂ n answers one question: how many times can I cut n in half until 1 is left? 8 → 4 → 2 → 1 is 3 halvings, so log₂ 8 = 3.
Any algorithm that throws away half of what's left at every step (binary search, walking down a , a 's sift-down) takes about log₂ n steps. It grows incredibly slowly: doubling n adds just one step.
Worked example
How many halvings for different n
- n = 1,000 → about 10 halvings (2¹⁰ = 1,024).
- n = 1,000,000 → about 20 (2²⁰ ≈ 1 million).
- n = 1,000,000,000 → about 30. A billion sorted items, found in 30 comparisons.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
n = 1,000
n after each halving
Solution · Pythonline 2
def halvings(n):steps = 0while n > 1:n //= 2steps += 1return steps # halvings(1_000_000) == 19, and math.log2(1_000_000) ≈ 19.9Step 1 of 11· line 2
log₂ n counts how many times n can be halved before it reaches 1. Watch 1,000 shrink.
Halving loops are . The base of the log doesn't matter in .
How to spot it
- The problem size is divided (by 2, 3, 10…) on every step.
- A balanced tree's height, a heap's height, the digits of a number (log₁₀ n).
Common mistakes
- Thinking O(log n) and are close: for n = 10⁹ it's 30 steps versus a billion.
- Calling a loop O(log n) when it subtracts 1 each time: that's O(n). It has to divide.
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →