TheScalableDev
FoundationsBeginner30 minlog2 of a million is about 20 · binary search needs floor(log2 n) + 1 comparisons · halving loops are O(log n)Free

Foundations - Logarithms for Engineers

Status

A logarithm asks how many times you can halve (or must double) to get from one number to another. This lesson builds the idea from scratch, gives you the log table to memorize, shows why binary search, balanced trees and heaps are O(log n) with exact step counts, and covers the floating-point traps that break real code.

Fold a sheet of paper in half again and again. After 10 folds you have 1,024 layers, after 20 folds more than a million. A logarithm runs that film backwards: given a million layers, it tells you the answer is about 20 folds. doubling is explosive, so its mirror image, halving, is nearly free. Every algorithm that throws away half of its remaining work each step (binary search, walking down a balanced tree, sifting through a heap) therefore finishes in a tiny number of steps, and that tiny number is the logarithm.

Builds on

  • Binary and bits — powers of two are exactly the values you can make from bits, and bit length is a logarithm.
  • Big-O notation — this lesson explains where the O(log n) row of the Big-O table comes from.
01

The idea: a logarithm undoes a power

Start with something you already know. Multiplying 2 by itself three times gives 8, written 2^3 = 8. The small raised 3 is called the exponent. Now ask the question backwards: 'I have 8 and I know the base is 2. What exponent got me here?' The answer, 3, is the logarithm of 8 to base 2, written log2(8) = 3. A logarithm is nothing more than the exponent you are looking for.

An everyday picture: a tournament bracket. Sixteen teams enter a knockout tournament. Each round, half the teams go home: 16, 8, 4, 2, 1. It takes 4 rounds to find a winner. So log2(16) = 4, and the same number answers two questions that look different. Going up: how many times must I double 1 to reach 16? Four. Going down: how many times can I halve 16 before one is left? Four.

2^4 = 16 <=> log2(16) = 4 · 2^10 = 1,024 <=> log2(1,024) = 10 · 2^0 = 1 <=> log2(1) = 0
Two ways to say the same fact. Notice log2(1) = 0: zero halvings are needed when you already have one item.

Precision matters here. For a number that is not an exact power of two, the exponent is a fraction. log2(100) is about 6.64, because 2^6 = 64 is too small and 2^7 = 128 is too big. When you count whole halvings of 100 using integer division you get floor(6.64) = 6: 100, 50, 25, 12, 6, 3, 1 is six cuts. When you ask how many bits it takes to write 100 you get floor(6.64) + 1 = 7 (it is 1100100 in binary). Keep both counts in mind: the exact logarithm is a decimal, and the whole-number counts are its floor or ceiling.

Written asSpoken asMeansExample
2^k = ntwo to the k equals nstart at 1, double k times2^5 = 32
log2(n) = klog base two of n is kthe k that makes the line above truelog2(32) = 5
halvings(n)number of whole halvingscuts from n down to 1, rounding down each timehalvings(100) = 6
bits(n)bit lengthbinary digits needed to write nbits(100) = 7
One idea, four ways you will meet it.

Check yourself

log2(32) equals what, and why?

02

The log table worth memorizing

You do not need a calculator for logarithms in interviews. You need about ten facts, and the REST is bracketing. The facts are the powers of two from 2^1 to 2^10, plus the anchors that 2^10 is about a thousand, 2^20 about a million, and 2^30 about a billion. These come from the fact that 2^10 = 1,024, which is very close to 1,000. Squaring and cubing it keeps the approximation tight.

nlog2(n)Why
212^1 = 2
422^2 = 4
832^3 = 8
1642^4 = 16
3252^5 = 32
6462^6 = 64
12872^7 = 128
25682^8 = 256 (one byte holds 256 values)
51292^9 = 512
1,024102^10 = 1,024
1,048,576202^20 = 1,024 x 1,024 = 1,048,576
1,000,00019.93just under 2^20 = 1,048,576
1,073,741,824302^30 = 1,048,576 x 1,024 = 1,073,741,824
1,000,000,00029.90just under 2^30
Exact powers of two give whole numbers. Round numbers like a million fall just below the next power.
log2(1,000,000) = log2(10^6) = 6 x log2(10) = 6 x 3.3219 = 19.93 · log2(1,000,000,000) = 9 x 3.3219 = 29.90
How the two decimals in the table are computed. log2(10) = 3.3219 is the single constant to remember: each decimal digit costs about 3.32 bits.

How to use the table for numbers that are not on it: bracket. To estimate log2(5,000), note that 2^12 = 4,096 and 2^13 = 8,192, so the answer lies between 12 and 13 (the exact value is 12.29). In an interview, 'a bit over 12' is the answer you want. You also get a free sanity check on any claim: if someone says a search over a billion items takes about a thousand steps, you know it should be about 30.

Generate the table yourself. Every line below was run in node.
1for (let k = 1; k <= 10; k++) console.log(2 ** k, "-> log2 =", Math.log2(2 ** k));
2console.log(Math.log2(1e6)); // 19.931568569324174
3console.log(Math.log2(1e9)); // 29.897352853986263
4console.log(Math.log2(2 ** 20), Math.log2(2 ** 30)); // 20 30

Check yourself

A table shows 2^20 = 1,048,576. Roughly what is log2(1,000,000)?

03

Counting halvings by hand

Let us count halvings of 1,000 with whole-number division, writing every step. 1,000 -> 500 -> 250 -> 125 -> 62 -> 31 -> 15 -> 7 -> 3 -> 1. That is 9 cuts, and floor(log2 1,000) = floor(9.97) = 9. Notice that 125 is odd, so halving it gives 62.5, and integer division drops the .5. Each rounding down can only make the next number smaller, so the count never exceeds the exact logarithm, and the count equals the floor.

The definition as code. This loop is O(log n): the counter shrinks by half each pass.
1function halvings(n) {
2 let steps = 0;
3 while (n > 1) {
4 n = Math.floor(n / 2);
5 steps++;
6 }
7 return steps;
8}
9console.log(halvings(1024)); // 10
10console.log(halvings(1000)); // 9
11console.log(halvings(1e6)); // 19
12console.log(halvings(1e9)); // 29

Now the trap that costs candidates points: the answer to 'how many times can I halve a million' is 19, but the answer to 'how many comparisons does binary search need on a million items' is 20. They differ by exactly one. The extra one is the final comparison against the last remaining item. Counting items versus counting cuts is the classic off-by-one, so always say which one you mean.

QuestionFormulan = 1,000,000n = 16
Whole halvings down to 1floor(log2 n)194
binary search, worst-case comparisonsfloor(log2 n) + 1205
Bits needed to write the number nfloor(log2 n) + 1205 (10000)
Bits to label n different items 0..n-1ceiling(log2 n)204
Height in edges of a packed tree with n nodesfloor(log2 n)194
Five questions, three formulas. Pick the formula by reading the question carefully.

Check yourself

A sorted array holds 16 items. In the worst case, how many comparisons does binary search need?

04

Why binary search, trees and heaps are O(log n)

Here is the connection that makes logarithms matter. binary search looks at the middle item of a sorted list. If the middle is too small, everything on its left is also too small, so that whole half is thrown away without being looked at. One comparison, half the list gone. Repeat until one item remains. The number of comparisons is the number of halvings, plus one for the final check.

comparisons(n) = floor(log2 n) + 1 -> n = 16: 5 · n = 1,000: 10 · n = 1,000,000: 20 · n = 1,000,000,000: 30
Worst-case comparisons for binary search. Measured by running the search in node on arrays of 16, 1,000 and 1,000,000 items; the billion row uses the same formula.
log2 n (binary search)
20
n (linear scan)
1,000,000

20 comparisons versus up to 1,000,000: the log bar is 50,000 times shorter (steps to handle n = 1,000,000 items)

Searching a million sorted items: at most 20 comparisons, versus up to a million for a linear scan.

Balanced binary trees behave the same way. In a binary search tree each node has two children, so the number of nodes you can hold doubles with every level: 1, then 3, then 7, then 15. A perfect tree with L levels holds 2^L - 1 nodes. Solve that backwards and the number of levels for n nodes is about log2(n + 1). With 1,048,575 nodes (that is 2^20 - 1) you need exactly 20 levels, so any lookup visits at most 20 nodes.

8412261014
A perfect tree with 7 nodes has 3 levels: 2^3 - 1 = 7. Looking up 10 visits 8, then 12, then 10. Three nodes, not seven.

A binary heap (the structure behind priority queues) is stored as a perfectly packed tree, filled level by level from left to right. With n items its height is floor(log2 n) edges. For 1,000,000 items that is 19 edges. Pushing an item adds it at the bottom and swaps it upward at most 19 times. Removing the minimum swaps the replacement downward at most 19 levels, with two child comparisons per level, so at most 38 comparisons. Both are O(log n).

StructureWhy log nn = 1,000n = 1,000,000
binary search on sorted arrayeach comparison halves the range10 comparisons20 comparisons
Balanced binary search tree lookupeach level doubles capacity10 levels20 levels
heap push or pop (edges swapped)height of a packed tree9 swaps19 swaps
Degenerate tree (all nodes in a chain)no halving: each level removes one node1,000 levels1,000,000 levels
The last row is the warning: O(log n) is a promise about balanced shape, not about the word 'tree'.

Check yourself

Why does a balanced binary search tree of one million values need only about 20 levels?

05

Change of base and the three rules

Three rules turn logarithms into arithmetic you can do in your head. They all come from one fact: multiplying numbers adds their exponents, because 2^a x 2^b = 2^(a+b). Read that sentence backwards and you have the product rule.

RuleStatementNumeric check (base 2)
Productlog(a x b) = log a + log blog2(8 x 16) = log2(128) = 7, and 3 + 4 = 7
Quotientlog(a / b) = log a - log blog2(1,024 / 8) = log2(128) = 7, and 10 - 3 = 7
Powerlog(a^k) = k x log alog2(8^4) = log2(4,096) = 12, and 4 x 3 = 12
Log of the baselog2(2) = 1 and log2(1) = 02^1 = 2 and 2^0 = 1
Each row was verified in node: Math.log2(8 * 16) = 7, Math.log2(1024 / 8) = 7, Math.log2(8 ** 4) = 12.

Why the rules matter in practice: the power rule says log2(n^2) = 2 x log2(n). So O(log(n^2)) is just O(2 log n), which is O(log n). Algorithms that look squared inside a logarithm do not get slower in the Big-O sense. It also explains why n log n sorting is only a little worse than linear: multiplying the input by 1,000 multiplies n by 1,000 but adds only about 10 to log n.

Now change of base. Suppose you know log10 but need log2. Since 2^k = n, take log10 of both sides: k x log10(2) = log10(n). So log2(n) = log10(n) / log10(2) = log10(n) x 3.3219. The conversion factor does not depend on n at all.

log2(n) = log10(n) x 3.3219 -> n = 1,000: 3 x 3.3219 = 9.97 · n = 1,000,000: 6 x 3.3219 = 19.93 · n = 1,000,000,000: 9 x 3.3219 = 29.90
The ratio log2(n) / log10(n) is 3.3219 at every size. I computed it in node for n = 1e3, 1e6 and 1e9 and got 3.321928094887362 each time (the last digit wobbles at 1e9 only from rounding).

This is the proof that the base does not matter in Big-O. If an algorithm does log2(n) steps, then a rewrite of the count in base 10 is log10(n) x 3.32, and in base e (natural log) it is ln(n) x 1.4427. Big-O drops constant multipliers, so O(log2 n), O(log10 n) and O(ln n) are all the same class, written O(log n). The base changes how many steps by a fixed factor, never how the count grows.

Baselog of 1,000,000Ratio to log2Common use
219.931bits, halving, binary search
e (ln)13.820.693calculus, growth rates, Math.log in JavaScript
1060.301decimal digits, orders of magnitude
Same input, three numbers, constant ratios (0.693 = ln 2 and 0.301 = log10 2).

Check yourself

An algorithm takes log2(n) steps. A friend says it is really log10(n) steps and the two are different complexities. What is the correct reply?

06

Logs as digit counts and log-scale thinking

Here is a use you have already met without the name. How many digits does the number 12,345 have? Five. How many times can you divide it by 10 before it drops below 10? Four (1,234, then 123, then 12, then 1). The digit count is always one more than the number of divisions, which is exactly floor(log10 n) + 1. A base-10 logarithm counts digits the way a base-2 logarithm counts bits.

nlog10(n)floor + 1Digits written out
90.9511
10122
991.99622
100233
12,3454.0955
1,000,000677
2^6419.272020 (it is 18,446,744,073,709,551,616)
The jump happens exactly at powers of ten: 99 has two digits, 100 has three.
digits of 2^64 = floor(64 x log10(2)) + 1 = floor(64 x 0.30103) + 1 = floor(19.27) + 1 = 20 · bits of 255 = floor(log2 255) + 1 = 7 + 1 = 8 · bits of 256 = 8 + 1 = 9
Power rule at work: log10(2^64) = 64 x log10(2). A number does not need to be written out to count its digits.

The same idea gives bit length. 255 is 11111111 in binary (eight ones), and 256 is 100000000 (a one followed by eight zeros, nine bits). The jump from 8 bits to 9 happens exactly at a power of two. That is why one byte holds 256 values (0 to 255) and why adding a single bit doubles the range of values you can store.

Log-scale intuition follows. On a normal axis, equal steps add the same amount (10, 20, 30). On a log axis, equal steps multiply by the same amount (10, 100, 1,000). Anything that spans many orders of magnitude, such as file sizes from bytes to gigabytes or response times from microseconds to seconds, only fits on a chart if the axis is logarithmic. When someone says 'orders of magnitude' they are speaking in log10: ten times bigger is one order, a thousand times bigger is three.

QuantityLinear viewLog2 viewWhat it means
Disk size 1 KB to 1 GB1,048,576 times bigger20 doublings20 steps of 'twice as much'
Sorted names 1,000 to 1,000,0001,000 times more data10 more comparisons (10 to 20)a thousand times the data, twice the search steps
Database rows 1M to 1B1,000 times more data10 more comparisons (20 to 30)same +10 again
Each 1,000x in size costs about +10 in the log, because 2^10 is about 1,000.

Check yourself

How many digits does the integer 1,000,000 have, using floor(log10 n) + 1?

07

Logarithmic versus exponential growth, plus ln and e

Exponential and logarithmic growth are inverses, which makes them opposite extremes. Exponential growth is a thing that doubles every step. Logarithmic growth is a thing that needs one extra step for every doubling of the input. One explodes, the other barely moves. Real counts make the contrast concrete.

k (or n)log2(n) stepsn (linear)2^k (exponential)At 1 billion ops/sec
103.32101,024about a microsecond
204.32201,048,576about a millisecond
304.91301,073,741,824about 1 second
405.32401,099,511,627,776about 18 minutes
505.64501,125,899,906,842,624about 13 days
605.91601,152,921,504,606,846,976about 36.5 years
Doubling the exponent from 30 to 60 turns one second into 36 years. The log column barely changes. Time column assumes one billion simple operations per second (an assumption, not a measurement) and was computed from 2^k / 10^9 seconds.
n = 1,000
9.97
n = 1,000,000
19.93
n = 1,000,000,000
29.9

Multiply the input by 1,000 and the answer grows by only about 10 (since 2^10 = 1,024) (log2 of the input size)

Log scale in action: multiplying n by 1,000 adds about 10 to the answer.

Interview consequence. An O(2^n) solution (try every subset) is hopeless past n = 40 or so. An O(log n) solution is effectively free at any size you could store in memory: even for 2^64 items, about 1.8 x 10^19, the answer is 64 steps. When you can turn a linear or exponential algorithm into a logarithmic one by halving the problem, that is almost always the intended insight.

A brief word on ln and e. The number e is about 2.71828. It is the base for which continuous growth looks cleanest, and the logarithm to that base is written ln. For us the only things to know are practical: ln(n) = log2(n) x 0.6931, so ln is a constant multiple of log2 and falls in the same Big-O class; ln(e) = 1; and in JavaScript, Python and most languages, the function called log or Math.log is the natural log, not log10. Math.log(1000) is 6.907755278982137, not 3.

Three functions, three bases. Output from node.
1console.log(Math.log(1000)); // 6.907755278982137 (natural log)
2console.log(Math.log10(1000)); // 3
3console.log(Math.log2(1000)); // 9.965784284662087
4console.log(Math.log(1000) / Math.log(2)); // 9.965784284662087 (change of base)

Check yourself

At one billion simple operations per second, about how long does an O(2^n) algorithm take for n = 50?

08

Floating-point traps and the interview script

Computers store decimals with limited precision, so most results of Math.log2 and its cousins are tiny approximations. Usually that is harmless. It becomes a bug the moment you apply floor, because floor turns 2.9999999999999996 into 2 and 3.0000000000000004 into 3. If the true answer is a whole number and the computer's answer is a hair below it, you lose a whole unit.

Real outputs from node. Each of these lines is a bug waiting to happen.
1console.log(Math.log(1000) / Math.log(10)); // 2.9999999999999996
2console.log(Math.floor(Math.log(1000) / Math.log(10))); // 2 (should be 3)
3console.log(Math.log10(1000)); // 3 (the dedicated function is right)
4console.log(Math.log2(2 ** 53 - 1)); // 53 (true value is just under 53)
5console.log(Math.floor(Math.log2(2 ** 53 - 1))); // 53 (should be 52)
6console.log(Math.floor(Math.log10(999999999999999)) + 1); // 16 (the number has 15 digits)

The pattern: dividing two natural logs to change base can land just under the true integer; and when n is within about one part in 10^15 of a power, even the dedicated Math.log2 and Math.log10 can round up to the whole number. For small powers of two and ten the dedicated functions happen to be exact (I tested every power of two to 2^60 and every power of ten to 10^22 and Math.log2 and Math.log10 were right), but you should not rely on that near the boundaries.

Three safe tools: integer loops, correction after the float estimate, and bit tricks.
1// 1) Exact digit count: divide by 10 until one digit remains
2function digits(n) {
3 let d = 1;
4 while (n >= 10) { n = Math.floor(n / 10); d++; }
5 return d;
6}
7
8// 2) floor(log2 n) with a correction step so rounding cannot hurt
9function floorLog2(n) {
10 let k = Math.floor(Math.log2(n));
11 while (2 ** k > n) k--; // estimate was too high
12 while (2 ** (k + 1) <= n) k++; // estimate was too low
13 return k;
14}
15
16// 3) Bit length for 32-bit integers, using Math.clz32 (count leading zeros)
17const bitLength = (n) => 32 - Math.clz32(n);
18
19console.log(digits(999999999999999)); // 15
20console.log(floorLog2(2 ** 53 - 1)); // 52
21console.log(floorLog2(1024), floorLog2(1023)); // 10 9
22console.log(bitLength(255), bitLength(256)); // 8 9
  • Prefer integers

    a loop that halves or divides by 10 uses exact integer arithmetic and cannot round the wrong way.

  • Correct the estimate

    compute the float, floor it, then nudge the result up or down until 2^k <= n < 2^(k+1).

  • Use bit operations

    for 32-bit values, 32 - Math.clz32(n) is the bit length with no floating point at all.

  • Guard the edges

    Math.log2(0) is -Infinity and Math.log2(-1) is NaN (not a number). Check n > 0 first.

  • Mind the 2^53 limit

    JavaScript numbers are exact integers only up to 2^53 - 1 = 9,007,199,254,740,991. Beyond it, use BigInt and toString(2).length.

How interviewers probe this. They want to hear that you can turn a halving loop into a bound, estimate with the table, and distinguish floor from ceiling. Below is a timed script for the usual question, 'why is binary search O(log n), and how many steps is that for a billion items?'

  1. 010:00 Claim

    Say it plainly: 'Each comparison throws away half of the remaining range, so the number of comparisons is how many times n can be halved.'

  2. 020:30 Show

    Pick a small case and trace it: 16 items cut to 8, 4, 2, 1. 'That is 4 halvings, 5 comparisons in the worst case, matching floor(log2 16) + 1.'

  3. 031:00 Scale

    'A thousand items is about 10 steps because 2^10 = 1,024. A million is about 20, a billion about 30. Multiplying the data by 1,000 adds only 10 steps.'

  4. 041:45 Base

    'The base does not matter in Big-O: log2(n) = 3.32 x log10(n), a constant, so I just write O(log n).'

  5. 052:15 Caveat

    'It needs a sorted array with O(1) random access, and for a tree it needs to be balanced. In code I would avoid floor(Math.log2(n)) near boundaries and use integer arithmetic.'

Check yourself

Which is the most reliable way to count the digits of a large positive integer in JavaScript?

Recap

  • log2(n) is the power you raise 2 to in order to get n, which is the same as the number of times you can halve n before reaching 1 (with whole-number halving the count is floor(log2 n)).

  • Memorize: 2^10 = 1,024, 2^20 = 1,048,576, 2^30 = 1,073,741,824. So log2 of a thousand is about 10, of a million about 20 (19.93), of a billion about 30 (29.90).

  • binary search on n items needs at most floor(log2 n) + 1 comparisons: 20 for a million items, 30 for a billion. A balanced tree or a heap of n items has height floor(log2 n).

  • doubling the input adds exactly one step to an O(log n) algorithm. Multiplying the input by 1,000 adds only about 10.

  • Rules: log(a x b) = log a + log b, log(a / b) = log a - log b, log(a^k) = k x log a. Check: log2(8 x 16) = 3 + 4 = 7 = log2(128).

  • Change of base: log2(n) = log10(n) x 3.3219..., a constant. That is why Big-O writes O(log n) with no base.

  • Digits in a positive integer = floor(log10 n) + 1. Bits in a positive integer = floor(log2 n) + 1.

  • Floating-point traps: floor(Math.log(1000) / Math.log(10)) gives 2, not 3, and Math.floor(Math.log10(999999999999999)) + 1 gives 16 digits for a 15-digit number. For exact integer counts, use loops, integer arithmetic, or verify with a correction step.

Terms in this lesson

Every acronym and concept, expanded. Tap a term to open it.

balanced tree

A tree kept roughly equal in height on both sides so operations stay O(log n).

binary search

Halving a sorted search space each step to find a value in O(log n).

linked list

A chain of nodes where each points to the next, giving cheap inserts and deletes but O(n) access.

logarithm

The inverse of exponentiation: log2(8) = 3 because 2^3 = 8. It answers 'what power of the base gives this number?'

algorithm

A precise, step-by-step procedure that solves a problem.

Big-O

Notation that describes how an algorithm's work grows as its input grows, ignoring constants and hardware.

array

A contiguous block of memory holding items in order, readable by index in O(1).

base

The number being raised to a power. log2 uses base 2, log10 uses base 10, and ln uses base e. Big-O ignores the base because bases differ by a constant factor.

RESTRepresentational State Transfer

An API style built on plain HTTP verbs (GET, POST, PUT, DELETE) where each URL names a resource.

byte

Eight bits, the standard unit for one character or small number.

heap

A tree where each parent is more extreme than its children, giving O(1) access to the min or max.

tree

A hierarchy of nodes where each node has one parent and zero or more children.

AVL

A self-balancing BST that rotates whenever two subtrees differ in height by more than one.

exponent

The small raised number in 2^10. It counts how many times the base is multiplied by itself.

halving

Cutting a quantity in half. Counting halvings from n down to 1 is the working definition of log2(n).

doubling

The reverse view: each +1 on the exponent doubles the value, so 2^20 is twice 2^19.

floor

Round down to the nearest whole number. floor(19.93) = 19. Used when counting whole steps.

ceiling

Round up to the nearest whole number. ceiling(19.93) = 20. The number of bits needed to label n different items is ceiling(log2 n).

lnnatural logarithm

The logarithm to base e (about 2.71828). In JavaScript, Math.log is ln, not log10 and not log2.

floating point

How computers store non-whole numbers using a fixed number of bits, which makes most results tiny approximations. This is why Math.log(1000) / Math.log(10) can come out as 2.9999999999999996.

bit length

How many binary digits a number needs. For a positive integer n it equals floor(log2 n) + 1.

Where you will see it

Real systems that use this exact idea. Tap a card to open it.

Common traps

The mistakes interviewers watch for. Guess the fix, then reveal it.

  1. FixIt needs 20 comparisons: floor(log2 n) + 1. The last remaining item still has to be checked.

  2. FixMath.log is the natural log. Use Math.log2 or Math.log10, and remember the base is a constant factor.

  3. FixUse an integer loop, Math.log10 with a correction step, or bit tricks to avoid being a unit off.

Interview prep

Questions you could be asked, with the depth an interviewer wants to hear.

Each comparison discards half of the remaining range, so the count of comparisons is the count of halvings: floor(log2 n) + 1 in the worst case.

halving count

Real worldgit bisect finds the first bad commit by binary search over the commit history.

DeeperTrace 16 items: 16, 8, 4, 2, 1, so 5 comparisons.