The Plain Picture#
Guess a number between 1 and 1,000. After each guess I say "higher" or "lower". The smart strategy: always guess the middle. Each answer throws away half of the remaining numbers:
1,000 → 500 → 250 → 125 → 63 → 32 → 16 → 8 → 4 → 2 → 1 about 10 guessesEven for 1,000,000 numbers you need only about 20 guesses. "How many times can I halve n until 1 is left?" — that number is the logarithm.
The Real Names#
log₂ n ("log base 2 of n") = the power you raise 2 to, to get n. Since 2¹⁰ = 1,024, log₂ 1,024 = 10. Equivalently: how many times you can halve n before reaching 1, or how many doublings from 1 reach n.
In complexity, "log n" means log₂ n unless stated otherwise. The base doesn't matter in Big-O: log₁₀ n and log₂ n differ only by a constant factor (log₂ n ≈ 3.32 × log₁₀ n), and constants are dropped.
| n | log₂ n (rounded) |
|---|---|
| 1,000 | 10 |
| 1,000,000 | 20 |
| 1,000,000,000 | 30 |
| 2³² ≈ 4.3 billion | 32 |
Logarithms grow incredibly slowly. Going from a thousand to a billion items — a million times more — only triples the steps.
Under the Hood — measured#
Binary search on a sorted array (fully taught in Binary Search (coming soon)), counting loop rounds for a value that isn't there:
binary search in 1000 items (not found): 9 steps
binary search in 1000000 items (not found): 19 steps
binary search in 100000000 items (not found): 26 stepsClose to log₂ n every time (≈10, 20, 27). And a loop that doubles its counter:
for (int i = 1; i < 1_000_000; i *= 2) count++;
// doubling loop to 1,000,000: 20 roundsWhere you'll see log n: binary search; balanced trees like TreeMap (Collections, From the Inside) — height log n; heaps
(PriorityQueue) — insert and remove in log n; the "log n" levels of divide-and-conquer sorting (Ch 8); and any loop where the problem size
is multiplied or divided by a constant each round.
Check yourself
3 questionsWhat's log₂ 64? log₂ 1,048,576?
Show answerHide answer
6; 20.
Why doesn't the base of the logarithm matter in Big-O?
Show answerHide answer
Logs of different bases differ only by a constant factor, which Big-O drops.
What's the complexity of for (int i = n; i > 1; i /= 3)?
Show answerHide answer
O(log n) — n is divided by a constant each round.