Skip to lesson

Halving loops and log n

A loop that adds or subtracts a constant (i++ or i -= 2) crawls across n in O(n) steps. A loop that multiplies or divides by a constant (i *= 2 or n /= 2) leaps across n in O(log n) steps—turning a billion items into roughly thirty checks.

Where log n comes from

Logarithmic time, O(log n), means the work grows very slowly because the problem size is halved at every step, as in binary search.

log₂(n) is how many times you can divide n by 2 before you get down to 1. Equivalently, it is how many times you must multiply 1 by 2 to reach n.

Halvings.javaJava
public class Halvings {    public static void main(String[] args) {        int n = 32, steps = 0;        while (n > 1) {            n /= 2;   // 32 -> 16 -> 8 -> 4 -> 2 -> 1            steps++;        }        System.out.println("log2(32) = " + steps);    }}
Output
log2(32) = 5

Try it with n = 32: 32 -> 16 -> 8 -> 4 -> 2 -> 1. That took 5 halving steps because 2⁵ = 32, so log₂(32) = 5. Every time n doubles, a halving process needs just one extra step!

  • n = 8: 8 -> 4 -> 2 -> 1 (3 halvings, so log2(8) = 3).
  • n = 64: 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 (6 halvings, so log2(64) = 6).
  • n = 1,024: 10 halvings, because 2¹⁰ = 1,024.
In Big O notation, we write O(log n) without a base because log_2(n), log_3(n), and log_10(n) differ only by a constant multiplier.

Loops that double or halve

You can spot an O(log n) loop immediately by looking at the update expression. Instead of i++ or i--, the variable is multiplied (i *= 2) or divided (n /= 2, n /= 10, or n >>= 1).

Example 1 · Tracing a halving loop and a doubling loop side by side

HalvingAndDoublingDemo.javaJava
public class HalvingAndDoublingDemo {    public static int countHalvings(int n) {        int steps = 0;        while (n > 1) {            n = n / 2;            steps++;        }        return steps;    }
    public static int countDoublings(int n) {        int steps = 0;        for (int i = 1; i < n; i *= 2) {            steps++;        }        return steps;    }
    public static void main(String[] args) {        System.out.println("n = 1,024        -> halvings = " + countHalvings(1024)            + ", doublings = " + countDoublings(1024));        System.out.println("n = 1,048,576    -> halvings = " + countHalvings(1_048_576)            + ", doublings = " + countDoublings(1_048_576));        System.out.println("n = 1,000,000,000 -> halvings = " + countHalvings(1_000_000_000));    }}
Output
n = 1,024        -> halvings = 10, doublings = 10
n = 1,048,576    -> halvings = 20, doublings = 20
n = 1,000,000,000 -> halvings = 29

What this code does

  • At n = 1,024 (2¹⁰), both loops run 10 times; at n = 1,048,576 (2²⁰), both run 20 times.
  • Even at one billion (1,000,000,000), halving down to 1 takes only 29 iterations (since 2²⁹ = 536,870,912 and 2³⁰ = 1,073,741,824).
  • Doubling up to n: for (int i = 1; i < n; i *= 2) -> runs ≈ log₂(n) times -> O(log n).
  • Halving down to 1: while (n > 1) { n /= 2; } -> runs ≈ log₂(n) times -> O(log n).
  • Stripping decimal digits: while (n > 0) { n /= 10; } -> runs ≈ log₁₀(n) times -> O(log n).
  • Nested linear + halving loop: an outer 0..n-1 loop containing an inner halving loop takes O(n log n) time.

For example, extracting the base-10 digits of a positive integer n uses while (n > 0) { n /= 10; }. Dividing by 10 on each step strips one digit per iteration, so the loop runs ⌊ log₁₀(n)⌋ + 1 times, which is O(log n).

log₂ of 10^9 is about 30

In coding interviews, you never need a calculator to estimate log₂(n). Memorize one golden fact: 2¹⁰ = 1,024 ≈ 10³ (one thousand).

Example 2 · Digit extraction with n /= 10 runs in O(log10 n) steps

DigitSumComplexityDemo.javaJava
public class DigitSumComplexityDemo {    // Strips one base-10 digit per step: O(log n) time, O(1) space    public static int sumOfDigits(int n) {        n = Math.abs(n);        int sum = 0;        int steps = 0;        while (n > 0) {            sum += n % 10;            n /= 10;            steps++;        }        System.out.println("Digit sum = " + sum + " (loop steps = " + steps + ")");        return sum;    }
    public static void main(String[] args) {        sumOfDigits(42);        sumOfDigits(987_654_321);    }}
Output
Digit sum = 6 (loop steps = 2)
Digit sum = 45 (loop steps = 9)

What this code does

  • For a 9-digit number like 987,654,321, n /= 10 runs exactly 9 times.
  • Because the number of digits in n is ⌊ log₁₀(n)⌋ + 1, any digit-by-digit loop runs in O(log n) time.
  1. 1,000 (10^3) ≈ 2^10 -> log2 is about 10.
  2. 1,000,000 (10^6) ≈ 2^20 -> log2 is about 20.
  3. 1,000,000,000 (10^9) ≈ 2^30 -> log2 is about 30.
  4. 2,147,483,647 (Integer.MAX_VALUE) = 2^31 - 1 -> log2 is 31.

Every time you multiply n by 1,000 (10³), you add 10 to log₂(n). So a million (10⁶ = 10³ × 10³) has log₂(10⁶) ≈ 20, and a billion (10⁹ = 10³ × 10³ × 10³) has log₂(10⁹) ≈ 30!

A first look at binary search

The most famous O(log n) algorithm is binary search, which finds a target value inside a sorted array. Instead of scanning from index 0 one element at a time, binary search checks the middle element nums[mid].

Binary search for 35 in a sorted array

Step 1 of 4

Array: 3, 8, 14, 21, 27, 35, 42, 50. low at index 0. high at index 7.
target
35
We look for 35 in a sorted array. low and high mark the range still possible: all 8 cells.

Example 3 · Brute force: linear search on a sorted array (O(n) time, O(1) space)

LinearSearchStepsDemo.javaJava
public class LinearSearchStepsDemo {    public static int linearSearchCountSteps(int[] sorted, int target) {        int steps = 0;        for (int i = 0; i < sorted.length; i++) {            steps++;            if (sorted[i] == target) {                System.out.println("Found at index " + i + " in " + steps + " steps");                return i;            }        }        System.out.println("Not found after " + steps + " steps");        return -1;    }
    public static void main(String[] args) {        int[] sorted = new int[1024];        for (int i = 0; i < sorted.length; i++) {            sorted[i] = i * 10;        }        linearSearchCountSteps(sorted, 10230); // last element        linearSearchCountSteps(sorted, 99999); // not present    }}
Output
Found at index 1023 in 1024 steps
Not found after 1024 steps

What this code does

  • Linear search checks the elements one by one, so the last element and a missing value both cost 1,024 steps.
  • It never uses the fact that the array is sorted.

Example 4 · Optimal: binary search on the sorted array (O(log n) time, O(1) space)

BinarySearchFirstLookDemo.javaJava
public class BinarySearchFirstLookDemo {    public static int binarySearchCountSteps(int[] sorted, int target) {        int low = 0;        int high = sorted.length - 1;        int steps = 0;        while (low <= high) {            steps++;            int mid = low + (high - low) / 2;            if (sorted[mid] == target) {                System.out.println("Found at index " + mid + " in " + steps + " steps");                return mid;            } else if (sorted[mid] < target) {                low = mid + 1;            } else {                high = mid - 1;            }        }        System.out.println("Not found after " + steps + " steps");        return -1;    }
    public static void main(String[] args) {        int[] sorted = new int[1024];        for (int i = 0; i < sorted.length; i++) {            sorted[i] = i * 10;        }        binarySearchCountSteps(sorted, 10230); // last element        binarySearchCountSteps(sorted, 99999); // not present    }}
Output
Found at index 1023 in 11 steps
Not found after 11 steps

What this code does

  • On the same 1,024 elements, binary search finishes in 11 steps instead of 1,024.
  • It is faster because the array is sorted: one comparison with the middle element rules out half of the remaining range, and halving 1,024 takes only about 10 rounds.
  • Requirement: The array must be sorted before binary search can work.
  • Each step cuts the active range high - low + 1 in half.
  • Worst-case comparisons for n elements: ⌊ log₂(n)⌋ + 1, which is O(log n) time and O(1) extra space.

Because the array is sorted, if nums[mid] is smaller than target, every element to the left of mid is also too small—so we throw away the entire left half by setting low = mid + 1. If nums[mid] is larger than target, we throw away the right half by setting high = mid - 1. Cutting the remaining range [low..high] in half on every step means even a sorted array of one billion elements takes at most 30 comparisons!

Order of execution

Run binary search

Tap the steps of one binary search, in the order they happen.

Next step

Check your understanding

10 quick questions