AlgoViz

Logarithms

easy 14 min

A 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

0:00 / 4:30

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.

Step 1 of 3

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?" (26=642^6 = 64). Logarithms ask the reverse: "how many 2s do I multiply to get 64?" (log⁡264=6\log_2 64 = 6). In computer science the base is almost always 2, because computers work in binary and algorithms split things in half.

The definition

log⁡bx=y  ⟺  b y=x\log_b x = y \iff b^{\,y} = x
bb is the base, xx is the number, and yy is the exponent: the answer. So log⁡28=3\log_2 8 = 3 because 23=82^3 = 8, and log⁡101000=3\log_{10} 1000 = 3 because 103=100010^3 = 1000.

Exponents and logs undo each other

The same three numbers, read in two directions.
  • Base bb

    What you multiply by. Base 2 in CS, base 10 for digits, base ee in maths.

  • Number xx

    The value you want to reach, such as the size of an array.

  • Answer yy

    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, log⁡2n\log_2 n 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 log⁡264=6\log_2 64 = 6.

The halving loop

Every O(log n) algorithm hides this loop: a problem that shrinks by half each round.
Python
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.97
Counting halvings gives the floor of log2 n.
Edit and run it in your browser

Memorise

Powers of two worth knowing

nnlog⁡2n\log_2 nnnlog⁡2n\log_2 n
211287
422568
835129
1641,02410
325about 1 millionabout 20
646about 1 billionabout 30
These values come up in every complexity estimate and interview.

The shortcut behind the big ones

210=1024≈103⇒log⁡21,000,000=log⁡2(103)2≈2×10=202^{10} = 1024 \approx 10^3 \quad\Rightarrow\quad \log_2 1{,}000{,}000 = \log_2 (10^3)^2 \approx 2 \times 10 = 20
Every factor of a thousand adds about 10 to log⁡2\log_2. So log⁡2109≈30\log_2 10^9 \approx 30 and log⁡21012≈40\log_2 10^{12} \approx 40.

The rules

Logarithm rules you will use

Product and quotient rules

log⁡b(xy)=log⁡bx+log⁡bylog⁡bxy=log⁡bx−log⁡by\log_b (xy) = \log_b x + \log_b y \qquad \log_b \frac{x}{y} = \log_b x - \log_b y
Logs turn multiplication into addition. log⁡2(8×4)=3+2=5\log_2 (8 \times 4) = 3 + 2 = 5, and indeed 32=2532 = 2^5.

Power rule

log⁡b(xk)=klog⁡bxsolog⁡(n2)=2log⁡n=O(log⁡n)\log_b (x^k) = k \log_b x \qquad\text{so}\qquad \log (n^2) = 2 \log n = O(\log n)
Squaring the input only doubles the log. That is why O(log⁡n2)O(\log n^2) is still written O(log⁡n)O(\log n).
RuleFormulaExample
Identitylog⁡bb=1\log_b b = 1, log⁡b1=0\log_b 1 = 0log⁡22=1\log_2 2 = 1; any base, log⁡1=0\log 1 = 0
Inverseblog⁡bx=xb^{\log_b x} = x2log⁡264=642^{\log_2 64} = 64
Productlog⁡(xy)=log⁡x+log⁡y\log(xy) = \log x + \log ylog⁡21024=log⁡232+log⁡232=10\log_2 1024 = \log_2 32 + \log_2 32 = 10
Powerlog⁡(xk)=klog⁡x\log(x^k) = k\log xlog⁡2220=20\log_2 2^{20} = 20
Change of baselog⁡bx=log⁡kxlog⁡kb\log_b x = \frac{\log_k x}{\log_k b}log⁡364=ln⁡64ln⁡3≈3.79\log_3 64 = \frac{\ln 64}{\ln 3} \approx 3.79

Big-O

Change of base: why the base does not matter

Change of base

log⁡bn=log⁡2nlog⁡2be.g.log⁡10n=log⁡2nlog⁡210≈log⁡2n3.32\log_b n = \frac{\log_2 n}{\log_2 b} \qquad\text{e.g.}\qquad \log_{10} n = \frac{\log_2 n}{\log_2 10} \approx \frac{\log_2 n}{3.32}
Any log can be written in any other base by dividing by a fixed number.

Since 1log⁡2b\frac{1}{\log_2 b} is just a constant, log⁡10n\log_{10} n, ln⁡n\ln n and log⁡2n\log_2 n are the same curve scaled up or down. Big-O ignores constant factors, so all of them are simply O(log⁡n)O(\log n). That is why complexity tables never write the base.

Every base is the same class

O(log⁡10n)=O(ln⁡n)=O(log⁡2n)=O(log⁡n)O(\log_{10} n) = O(\ln n) = O(\log_2 n) = O(\log n)
The base still matters for exact counts: a B-tree that branches 100 ways has height about log⁡100n\log_{100} n, far shorter than a binary tree's log⁡2n\log_2 n.

In code

Logarithms in Python

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)
The math module covers every base you need.
Edit and run it in your browser
CallMeaningUse it for
math.log2(n)log⁡2n\log_2 n as a floatEstimating steps, tree heights
math.log10(n)log⁡10n\log_{10} n as a floatRough digit counts
math.log(n, b)log⁡bn\log_b n via change of baseAny other base
n.bit_length() - 1⌊log⁡2n⌋\lfloor \log_2 n \rfloor, exactInteger answers, huge numbers
Other languages: 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)

nnO(n)O(n) linearO(log⁡n)O(\log n)Speedup
1,0001,00010100×
1,000,0001,000,0002050,000×
1,000,000,0001 billion3033 million×
Going from a thousand to a billion items adds only about 20 steps to an O(log n) algorithm.

Why it grows so slowly

log⁡2(2n)=log⁡2n+1log⁡2(1000 n)≈log⁡2n+10\log_2 (2n) = \log_2 n + 1 \qquad \log_2 (1000\,n) \approx \log_2 n + 10
The input has to grow a thousandfold for the cost to grow by ten steps.
Binary search as data grows
  1. 11 thousand itemsabout 10 comparisons
  2. 21 million itemsabout 20 comparisons
  3. 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

Each pass discards half of what is left. Finding 42 in 1 to 64 takes 5 passes.

Counting the steps

n→n2→n4→⋯→n2k=1⇒k=log⁡2nn \to \frac{n}{2} \to \frac{n}{4} \to \dots \to \frac{n}{2^k} = 1 \quad\Rightarrow\quad k = \log_2 n
After kk comparisons at most n/2kn / 2^k items remain. The search ends when that reaches 1, so at most about log⁡2n\log_2 n comparisons: about 20 for a million items.
  • 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 nn commits in about log⁡2n\log_2 n test runs.

  • Standard libraries

    Python's bisect, C++'s std::binary_search, Java's Arrays.binarySearch.

Trees

Tree height is log n

Each level doubles

A balanced binary tree fills each level before starting the next.

From node count to height

1+2+4+⋯+2h=2h+1−1≥n⇒h=⌊log⁡2n⌋1 + 2 + 4 + \dots + 2^{h} = 2^{h+1} - 1 \ge n \quad\Rightarrow\quad h = \lfloor \log_2 n \rfloor
A tree of height hh (edges from root to deepest leaf) holds up to 2h+1−12^{h+1} - 1 nodes, so nn nodes need height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor, or ⌈log⁡2(n+1)⌉\lceil \log_2 (n+1) \rceil levels.
NodesHeight (edges)Levels
1534
1,0241011
about 1 millionabout 20about 20
about 1 billionabout 30about 30
Search, insert and delete walk one root-to-leaf path, so they cost O(log n) while the tree stays balanced.
  • 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 log⁡100+n\log_{100+} n: a few disk reads for billions of rows.

  • Heap

    A complete tree: push and pop move one value up or down log⁡2n\log_2 n levels.

Pattern spotting

Recognising O(log n)

Is this logarithmic?

Merge sort splits in half too, but it works on every item at every level, giving nlog⁡nn \log n.

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 log⁡n\log n 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 xnx^n by squaring, O(log⁡n)O(\log n) multiplications.

  • Fenwick tree

    Prefix sums with updates in O(log⁡n)O(\log n).

  • Segment tree

    Range queries and updates on arrays.

  • Heap operations

    Insert and extract the minimum or maximum.

Logarithmic

  • n //= 2 or n //= 10 inside a loop.
  • i *= 2 until i reaches n.
  • Recursing on one half and ignoring the other.
  • Following one path down a balanced tree.

Not logarithmic

  • n -= 2 or i += 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

  • log⁡bx=y\log_b x = y means by=xb^y = x: a log asks which power gives the number.
  • For programmers, log⁡2n\log_2 n is how many times you can halve nn before reaching 1.
  • Any algorithm that divides its input by a constant each step is O(log n); doubling nn adds one step.
  • Know the anchors: log⁡21024=10\log_2 1024 = 10, log⁡2106≈20\log_2 10^6 \approx 20, log⁡2109≈30\log_2 10^9 \approx 30.
  • A balanced binary tree with nn nodes has height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor, so tree operations are O(log n).
  • Bases differ only by a constant factor, so Big-O just writes O(log n).
  • Use bit_length or integer loops when you need an exact integer log.

Sources