AlgoTales · Roadmap

Logarithms

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A logarithm answers: how many times can I cut something in half before only one piece is left? It is the reason searches on sorted data, balanced trees and database indexes stay quick even when data grows enormously: a million items need about twenty halvings.

Practical use cases

  • Web app: Autocomplete over a million names. A sorted list of a million customers is searched by repeatedly checking the middle. Each check throws away half, so about twenty checks find any name. Doubling the customers to two million adds just one more check, which is why the suggestions stay instant.
  • Web app: Why database indexes stay fast. A MySQL index is a tree that narrows down by a big fraction at every step. Finding one order among ten million takes only a few hops, not millions of row reads. This is why adding an index can turn a four-second page into an instant one.
  • System: How many bits or digits do I need. To give unique numbers to a million items you need about 20 bits, and a number with a million in it has 7 digits. Both are logarithm answers. Engineers use them to choose ID sizes, hash lengths and how much storage a table will need.

The story: The Laddoo Halving Game

Raju's stall had a pile of 64 laddoos for Diwali, and Mira challenged him to a game. "Cut the pile in half. Keep one half, give the other away. Repeat. How many cuts until one laddoo is left?" Raju counted on his fingers: 32, 16, 8, 4, 2, 1. "Six cuts!"

Kabir joined in. "What if the pile had 128 laddoos, double the size?" Raju thought. "One extra cut: 128 becomes 64, and then it is the same game." Mira was amazed. "So doubling the pile adds just one cut? What about a thousand laddoos?" Raju grinned. "About ten cuts. A thousand and a bit more still only ten."

Mrs. Sharma, passing by, smiled. "You have just discovered the logarithm. It does not need a formula. It is simply: how many times can I halve this until nothing is left to halve?" That is why binary search is fast: every look throws away half the choices, so even a million names need only about twenty looks.

Whenever you hear "O(log n)", picture Raju cutting a pile. Even if the pile grows to the size of the whole city, he will finish before his chai gets cold.

How to spot this problem, and where you need it

You need to explain or predict why some operations barely slow down as data grows to millions, while others slow down in proportion, and decide which one your feature behaves like.

Signs you need it

  • Each step of your algorithm throws away half, a third or some fixed share of what is left.
  • Doubling the data adds only one more step instead of doubling the work.
  • You are asking how many levels, digits, bits or rounds are needed to cover N things.
  • A problem statement hints at a huge input limit with a short time limit, suggesting halving or a tree.

Where to use it in a project

  • Choosing sorted data and halving search over a plain loop for lookups in a large in-memory list.
  • Justifying a database index or a tree-based structure when a table is expected to grow into millions of rows.

The solution

Ask yourself: can each step discard a big portion of the remaining data? If yes, arrange your data so that this is possible: keep it sorted, or store it in a tree, so a single comparison tells you which half to ignore. Then repeat the comparison until one item remains. The number of steps is the number of halvings, which stays small even for gigantic data.

Payoff: Before: up to 1,000,000 checks to find one name. After: about 20 checks, and only 21 if the data doubles.

Explain it like I am 8

Take a long chocolate bar and keep breaking it in half and eating one half. The number of breaks before you are down to one tiny square is the logarithm. Even a giant bar needs only a few breaks.

How it works, step by step

  1. Take a size, for example 64.
  2. Halve it (throw away half): 64 becomes 32.
  3. Count that cut and keep halving: 16, 8, 4, 2, 1, with one count each time.
  4. Stop at 1. The count you have made is the logarithm (base 2) of the starting size.
  5. Remember the effect: double the size and the count goes up by just 1, so it grows super slowly.

The code in four languages

PHP

<?php
// How many times can we halve n until we reach 1?  (the base-2 logarithm, rounded down)
function halvings(int $n): int {
    $cuts = 0;
    while ($n > 1) {
        $n = intdiv($n, 2);    // keep one half
        $cuts++;
    }
    return $cuts;
}

foreach ([8, 64, 128, 1000, 1000000] as $pile) {
    echo "pile of $pile -> " . halvings($pile) . " cuts
";
}

// The same idea with 10 instead of 2 counts the digits of a number.
function digits(int $n): int {
    $d = 1;
    while ($n >= 10) { $n = intdiv($n, 10); $d++; }
    return $d;
}
echo "digits in 987654: " . digits(987654) . "
";

JavaScript

// How many times can we halve n until we reach 1?  (the base-2 logarithm, rounded down)
function halvings(n) {
  let cuts = 0;
  while (n > 1) {
    n = Math.floor(n / 2);     // keep one half
    cuts++;
  }
  return cuts;
}

for (const pile of [8, 64, 128, 1000, 1000000]) {
  console.log("pile of " + pile + " -> " + halvings(pile) + " cuts");
}

// The same idea with 10 instead of 2 counts the digits of a number.
function digits(n) {
  let d = 1;
  while (n >= 10) { n = Math.floor(n / 10); d++; }
  return d;
}
console.log("digits in 987654: " + digits(987654));

Java

public class Main {
    // How many times can we halve n until we reach 1?  (the base-2 logarithm, rounded down)
    static int halvings(int n) {
        int cuts = 0;
        while (n > 1) {
            n = n / 2;             // keep one half
            cuts++;
        }
        return cuts;
    }

    // The same idea with 10 instead of 2 counts the digits of a number.
    static int digits(int n) {
        int d = 1;
        while (n >= 10) { n = n / 10; d++; }
        return d;
    }

    public static void main(String[] args) {
        for (int pile : new int[]{8, 64, 128, 1000, 1000000}) {
            System.out.println("pile of " + pile + " -> " + halvings(pile) + " cuts");
        }
        System.out.println("digits in 987654: " + digits(987654));
    }
}

Go

package main

import "fmt"

// halvings: how many times can we halve n until we reach 1? (the base-2 logarithm, rounded down)
func halvings(n int) int {
	cuts := 0
	for n > 1 {
		n /= 2 // keep one half
		cuts++
	}
	return cuts
}

// digits: the same idea with 10 instead of 2 counts the digits of a number.
func digits(n int) int {
	d := 1
	for n >= 10 {
		n /= 10
		d++
	}
	return d
}

func main() {
	for _, pile := range []int{8, 64, 128, 1000, 1000000} {
		fmt.Printf("pile of %d -> %d cuts\n", pile, halvings(pile))
	}
	fmt.Println("digits in 987654:", digits(987654))
}

Time: O(log n) · Extra space: O(1). The loop runs once per halving, and a pile of n can only be halved about log n times.

Watch out for

  • Thinking log n is nearly the same as n. It is far smaller: a million items give only about 20.
  • Forgetting that the base matters in meaning but not in Big-O: halving, thirding or tenthing all give "O(log n)".
  • Trying to take the log of 0 or a negative number. Halving never reaches 1 from 0.

Quick check

  1. How many halvings does a pile of 16 need to reach 1?
    • 3
    • 4
    • 8
  2. If the pile doubles, the number of cuts...
    • Doubles too
    • Goes up by 1
    • Stays the same
  3. Which is the fastest growing?
    • log n
    • n
    • n squared