Foundations - Logarithms for Engineers
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.
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.
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 as | Spoken as | Means | Example |
|---|---|---|---|
| 2^k = n | two to the k equals n | start at 1, double k times | 2^5 = 32 |
| log2(n) = k | log base two of n is k | the k that makes the line above true | log2(32) = 5 |
| halvings(n) | number of whole halvings | cuts from n down to 1, rounding down each time | halvings(100) = 6 |
| bits(n) | bit length | binary digits needed to write n | bits(100) = 7 |
Check yourself
log2(32) equals what, and why?
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.
| n | log2(n) | Why |
|---|---|---|
| 2 | 1 | 2^1 = 2 |
| 4 | 2 | 2^2 = 4 |
| 8 | 3 | 2^3 = 8 |
| 16 | 4 | 2^4 = 16 |
| 32 | 5 | 2^5 = 32 |
| 64 | 6 | 2^6 = 64 |
| 128 | 7 | 2^7 = 128 |
| 256 | 8 | 2^8 = 256 (one byte holds 256 values) |
| 512 | 9 | 2^9 = 512 |
| 1,024 | 10 | 2^10 = 1,024 |
| 1,048,576 | 20 | 2^20 = 1,024 x 1,024 = 1,048,576 |
| 1,000,000 | 19.93 | just under 2^20 = 1,048,576 |
| 1,073,741,824 | 30 | 2^30 = 1,048,576 x 1,024 = 1,073,741,824 |
| 1,000,000,000 | 29.90 | just under 2^30 |
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.
for (let k = 1; k <= 10; k++) console.log(2 ** k, "-> log2 =", Math.log2(2 ** k));console.log(Math.log2(1e6)); // 19.931568569324174console.log(Math.log2(1e9)); // 29.897352853986263console.log(Math.log2(2 ** 20), Math.log2(2 ** 30)); // 20 30Check yourself
A table shows 2^20 = 1,048,576. Roughly what is log2(1,000,000)?
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.
function halvings(n) { let steps = 0; while (n > 1) { n = Math.floor(n / 2); steps++; } return steps;}console.log(halvings(1024)); // 10console.log(halvings(1000)); // 9console.log(halvings(1e6)); // 19console.log(halvings(1e9)); // 29Now 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.
| Question | Formula | n = 1,000,000 | n = 16 |
|---|---|---|---|
| Whole halvings down to 1 | floor(log2 n) | 19 | 4 |
| binary search, worst-case comparisons | floor(log2 n) + 1 | 20 | 5 |
| Bits needed to write the number n | floor(log2 n) + 1 | 20 | 5 (10000) |
| Bits to label n different items 0..n-1 | ceiling(log2 n) | 20 | 4 |
| Height in edges of a packed tree with n nodes | floor(log2 n) | 19 | 4 |
Check yourself
A sorted array holds 16 items. In the worst case, how many comparisons does binary search need?
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.
20 comparisons versus up to 1,000,000: the log bar is 50,000 times shorter (steps to handle n = 1,000,000 items)
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.
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).
| Structure | Why log n | n = 1,000 | n = 1,000,000 |
|---|---|---|---|
| binary search on sorted array | each comparison halves the range | 10 comparisons | 20 comparisons |
| Balanced binary search tree lookup | each level doubles capacity | 10 levels | 20 levels |
| heap push or pop (edges swapped) | height of a packed tree | 9 swaps | 19 swaps |
| Degenerate tree (all nodes in a chain) | no halving: each level removes one node | 1,000 levels | 1,000,000 levels |
Check yourself
Why does a balanced binary search tree of one million values need only about 20 levels?
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.
| Rule | Statement | Numeric check (base 2) |
|---|---|---|
| Product | log(a x b) = log a + log b | log2(8 x 16) = log2(128) = 7, and 3 + 4 = 7 |
| Quotient | log(a / b) = log a - log b | log2(1,024 / 8) = log2(128) = 7, and 10 - 3 = 7 |
| Power | log(a^k) = k x log a | log2(8^4) = log2(4,096) = 12, and 4 x 3 = 12 |
| Log of the base | log2(2) = 1 and log2(1) = 0 | 2^1 = 2 and 2^0 = 1 |
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.
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.
| Base | log of 1,000,000 | Ratio to log2 | Common use |
|---|---|---|---|
| 2 | 19.93 | 1 | bits, halving, binary search |
| e (ln) | 13.82 | 0.693 | calculus, growth rates, Math.log in JavaScript |
| 10 | 6 | 0.301 | decimal digits, orders of magnitude |
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?
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.
| n | log10(n) | floor + 1 | Digits written out |
|---|---|---|---|
| 9 | 0.95 | 1 | 1 |
| 10 | 1 | 2 | 2 |
| 99 | 1.996 | 2 | 2 |
| 100 | 2 | 3 | 3 |
| 12,345 | 4.09 | 5 | 5 |
| 1,000,000 | 6 | 7 | 7 |
| 2^64 | 19.27 | 20 | 20 (it is 18,446,744,073,709,551,616) |
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.
| Quantity | Linear view | Log2 view | What it means |
|---|---|---|---|
| Disk size 1 KB to 1 GB | 1,048,576 times bigger | 20 doublings | 20 steps of 'twice as much' |
| Sorted names 1,000 to 1,000,000 | 1,000 times more data | 10 more comparisons (10 to 20) | a thousand times the data, twice the search steps |
| Database rows 1M to 1B | 1,000 times more data | 10 more comparisons (20 to 30) | same +10 again |
Check yourself
How many digits does the integer 1,000,000 have, using floor(log10 n) + 1?
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) steps | n (linear) | 2^k (exponential) | At 1 billion ops/sec |
|---|---|---|---|---|
| 10 | 3.32 | 10 | 1,024 | about a microsecond |
| 20 | 4.32 | 20 | 1,048,576 | about a millisecond |
| 30 | 4.91 | 30 | 1,073,741,824 | about 1 second |
| 40 | 5.32 | 40 | 1,099,511,627,776 | about 18 minutes |
| 50 | 5.64 | 50 | 1,125,899,906,842,624 | about 13 days |
| 60 | 5.91 | 60 | 1,152,921,504,606,846,976 | about 36.5 years |
Multiply the input by 1,000 and the answer grows by only about 10 (since 2^10 = 1,024) (log2 of the input size)
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.
console.log(Math.log(1000)); // 6.907755278982137 (natural log)console.log(Math.log10(1000)); // 3console.log(Math.log2(1000)); // 9.965784284662087console.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?
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.
console.log(Math.log(1000) / Math.log(10)); // 2.9999999999999996console.log(Math.floor(Math.log(1000) / Math.log(10))); // 2 (should be 3)console.log(Math.log10(1000)); // 3 (the dedicated function is right)console.log(Math.log2(2 ** 53 - 1)); // 53 (true value is just under 53)console.log(Math.floor(Math.log2(2 ** 53 - 1))); // 53 (should be 52)console.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.
// 1) Exact digit count: divide by 10 until one digit remainsfunction digits(n) { let d = 1; while (n >= 10) { n = Math.floor(n / 10); d++; } return d;} // 2) floor(log2 n) with a correction step so rounding cannot hurtfunction floorLog2(n) { let k = Math.floor(Math.log2(n)); while (2 ** k > n) k--; // estimate was too high while (2 ** (k + 1) <= n) k++; // estimate was too low return k;} // 3) Bit length for 32-bit integers, using Math.clz32 (count leading zeros)const bitLength = (n) => 32 - Math.clz32(n); console.log(digits(999999999999999)); // 15console.log(floorLog2(2 ** 53 - 1)); // 52console.log(floorLog2(1024), floorLog2(1023)); // 10 9console.log(bitLength(255), bitLength(256)); // 8 9Prefer 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?'
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.'
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.'
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.'
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).'
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.
FixIt needs 20 comparisons: floor(log2 n) + 1. The last remaining item still has to be checked.
FixMath.log is the natural log. Use Math.log2 or Math.log10, and remember the base is a constant factor.
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.