← Math
Math

Powers of two and logarithms

Which ring can the server afford?

Choose a power-of-two capacity that covers a target and respects a budget.

Outcome

Use ⌈log₂⌉ to cover a target and ⌊log₂⌋ to fit a limit, count id bits exactly, and say which limit decides.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Power of two Also 2ᵏ
A number made by doubling 1 k times: 1, 2, 4, 8, … Ring buffers, textures and hash tables often require one.
Logarithm base 2 Also log₂
The exponent k with 2ᵏ = x. log₂ 256 = 8; log₂ 150 ≈ 7.23.
Bit length
The number of binary digits needed to write a whole number: 255 needs 8, 256 needs 9, 0 needs none.
Ceiling of log₂ Also ⌈log₂ n⌉
The smallest k with 2ᵏ ≥ n: the exponent of the smallest power of two that covers n.
Floor of log₂ Also ⌊log₂ m⌋
The largest k with 2ᵏ ≤ m: the exponent of the largest power of two that fits under m.
Overflow
A result too large for its integer type. Unsigned types in Go and C++ wrap around; Rust debug builds stop the program.

Why this matters

Many ring buffers and hash tables use power-of-two sizes; id fields offer a power-of-two number of bit patterns. Sizing one is a logarithm question with a direction: cover a target by rounding the exponent up, fit a limit by rounding it down. Using the wrong direction allocates too little or more than the budget allows. At large sizes, floating logarithms and 64-bit products stop being exact.

This lesson assumes exponents and whole-number division. Byte budgets here ignore allocator overhead and alignment.

Powers grow a capacity; logarithms find an exponent

A power of two, 2ᵏ, starts at one and doubles k times for a nonnegative whole exponent. The base-two logarithm reverses that question: log₂ x asks which exponent produces x. Values between consecutive powers have logarithms between the corresponding whole exponents.

A capacity restricted to powers of two has discrete choices. Covering a target asks for the smallest allowed capacity at least as large as the target; fitting a budget asks for the largest allowed capacity within its limit. Bits provide a related count: each additional bit doubles the number of distinct patterns available for identifiers.

01Define the quantities

The ring and its two limits

A telemetry ingest service buffers recent events in a ring whose power-of-two size lets it calculate a slot index with a bit mask. The team wants room for 150 events, but memory also limits how many slots it can allocate. Which ring covers the target without exceeding that budget?

Event ring inputs
QuantityMeaningWorked value
TargetEvents the ring must hold, at least150
Slot sizeBytes per event2,048
BudgetBytes the ring may use, at most600,000
RingA power of two satisfying bothunknown

02Count the bits

Count the bits that number n things

Each of 256 slots needs an id from 0 to 255. How many bits does the id field need?

03Cover a target

Cover a target: round the exponent up

log₂ 150 ≈ 7.23. The ring must hold at least 150, so the exponent rounds up to 8 and the ring is 2⁸ = 256. Rounding to the nearest exponent gives 128, which holds too few. An exact power covers itself: a target of 128 needs a ring of 128, not 256.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const bitLength = (n: bigint) => (n === 0n ? 0 : n.toString(2).length);

const bits = (n: bigint) => bitLength(n - 1n); // ids 0 .. n-1
const cover = (n: bigint) => 1n << BigInt(bits(n)); // smallest power >= n
const fit = (m: bigint) => 1n << BigInt(bitLength(m) - 1); // largest power <= m (m >= 1)

const slots = 2_000_000n / 4096n; // whole slots the budget pays for

console.log(`bits ${bits(256n)} ${bits(257n)}`);
console.log(`cover ${cover(150n)}`);
console.log(`fit ${fit(slots)}`);

BigInt keeps integers exact past 2⁵³, and toString(2).length is its bit length (0n needs a special case). Math.clz32 counts leading zeros only for 32-bit values. There is no built-in round-up or round-down to a power.

Each version prints the bits for 256 and 257 ids, the ring covering 150, and the largest power fitting 488 whole slots: bits 8 9, cover 256, fit 256.

04Fit under a maximum

Fit under a maximum: round the exponent down

The budget pays for ⌊600,000 ÷ 2,048⌋ = 292 whole slots. A ring may be at most 292, so the exponent rounds down: log₂ 292 ≈ 8.19, giving 2⁸ = 256. If the budget paid for exactly 256 slots, 256 would still fit; halving a rounded-up answer would wrongly give 128.

The target grows to 300 events with the same budget. What should the review say?

05Keep large counts exact

Keep large counts exact

A double has 53 bits of precision. Predict what this program prints for one more than 2⁵³.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const n = 2 ** 53 + 1; // one more than a power of two

console.log(Math.ceil(Math.log2(n)));
What does this program print?

06Vary inputs, then decide

Vary one input at a time, then decide

2,048-byte slots
Target, budgetWhole slotsCovers targetDecision
150, 600,000 B292256ring 256
300, 600,000 B292512none; budget allows 256
300, 1,048,576 B512512ring 512
128, 262,144 B128128ring 128
1, 1,000 B01none; no slot fits

07Size the ring

Build one ring planner

Give each event slot a distinct id, then choose the smallest ring that can hold the requested target. Once the caller supplies a byte budget, the same helper is no longer enough: the planner must also find the largest ring the budget permits. Each task supplies the other working helpers and its complete input path.

In the frontend Texture atlases in Next.js and Svelte Optional

WebGL 1 can mipmap or repeat a texture only when both sides are powers of two; WebGL 2 lifts that requirement. A 1,500 × 900 sprite sheet is padded to 2,048 × 1,024: each side covers up on its own. MAX_TEXTURE_SIZE is an upper limit, so the largest usable side rounds down.

Both excerpts use Math.clz32, which counts leading zeros in a 32-bit value, so they are exact only up to 2³¹. The Next.js helper takes the WebGL context; the Svelte component derives the atlas size from its props.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
'use client';

// Smallest power of two at or above n, for 1 <= n <= 2 ** 31.
const cover = (n: number) => (n <= 1 ? 1 : 2 ** (32 - Math.clz32(n - 1)));
// Largest power of two at or below m, for 1 <= m < 2 ** 32.
const fit = (m: number) => 2 ** (31 - Math.clz32(m));

export function atlasSize(width: number, height: number, gl: WebGLRenderingContext) {
  const max = fit(gl.getParameter(gl.MAX_TEXTURE_SIZE));
  const w = cover(width);
  const h = cover(height);

  return w <= max && h <= max ? { w, h } : null; // each side rounds on its own
}

Check this idea later
A hash-table configuration requires at least 1,000 buckets and a power-of-two bucket count. What is the smallest allowed count?
How many bits does an id need to number 1,024 devices?
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.