Algorithms

Logarithm: how many rounds does a 16-team knockout have?

Cover of the article Logarithm: how many rounds does a 16-team knockout have?
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. How does the logarithm relate to powers?
  2. How do you calculate a logarithm by counting divisions?
  3. Why does the logarithm show up in algorithms?
  4. Now you ask: what about the n × log n of sorting?
  5. Which base: 2, 10 or e?
  6. What are the most common mistakes with logarithms?
  7. Now it’s your turn!

A logarithm is the exponent to which a base must be raised to reach a number. The base-2 logarithm of 8 is 3, because 2 to the power of 3 is 8. Put another way, it answers a question: how many times do I have to use the base in a multiplication to get there?

In the article on binary search, you played the game of guessing a number from 1 to 100, always guessing the middle. A question was left hanging: how many guesses, at most, does that game take? Seven. And for a number from 1 to 1 million? Twenty. This calculation has a name, logarithm, and it shows up again in several algorithms of this journey, like merge sort, quicksort and heapsort. If the word reminds you of a hard high school class, take a breath: here we only need one idea, and it fits in a tournament bracket. And if powers still aren’t solid for you, go through the article on exponentiation and exponential growth first: the logarithm is the same calculation, done backwards.

Think of a knockout tournament with 16 teams. After the first round, 8 are left. After the second, 4. After the third, 2. In the fourth, the champion comes out. That’s 4 rounds for 16 teams. If the tournament doubles in size, to 32 teams, how many more rounds? Just one! The number of rounds is the base-2 logarithm of the number of teams.

Diagram of a knockout tournament with 16 teams that drops to 8, 4, 2 and 1 in four rounds, showing that the base-2 logarithm of 16 is 4
The base-2 logarithm counts how many times you can divide by 2 until you reach 1.

How does the logarithm relate to powers?

The logarithm is the power read backwards. Think of a sheet of paper folded in half again and again: each fold doubles the layers. With powers, you know the number of folds and want the layers. Here it’s the other way around: the sheet is already folded, and the question is how many folds there were.

Three-panel comic: a folded sheet has 8 layers; undoing the folds, it goes to 4, 2 and 1, and the three divisions by 2 are the base-2 logarithm of 8
The sheet with 8 layers: three divisions by 2 until you reach 1. The base-2 logarithm of 8 is 3.

With powers, you know the exponent and want the result. With logarithms, you know the result and want the exponent. It’s the table of powers of 2, read from right to left:

PowerLogarithmHow you read it
23 = 8log2 8 = 3Log base 2 of 8 is 3
24 = 16log2 16 = 4Log base 2 of 16 is 4
210 = 1,024log2 1,024 = 10Log base 2 of 1,024 is 10
103 = 1,000log10 1,000 = 3Log base 10 of 1,000 is 3
The same information written as a power and as a logarithm.

In Python, the math module does the calculation:

import math

print(math.log2(8))
print(math.log2(1024))
print(math.log10(1000))
print(math.log2(1000))

Output:

3.0
10.0
3.0
9.965784284662087

The first three answers are exact, because 8, 1,024 and 1,000 are round powers of the base. The last one isn’t: 1,000 is between 29, which is 512, and 210, which is 1,024. That’s why the logarithm came out between 9 and 10.

How do you calculate a logarithm by counting divisions?

There’s a way to see the base-2 logarithm without any formula: count how many times you can divide the number by 2 until you reach 1. It’s the knockout tournament, round by round. Look at it in Python:

def count_divisions(number):
    divisions = 0
    while number > 1:
        number = number // 2
        divisions += 1
    return divisions


for number in [8, 1000, 1024, 1000000]:
    print(number, count_divisions(number))

Output:

8 3
1000 9
1024 10
1000000 19

For 8 and 1,024, the count matches math.log2. For 1,000, it came out as 9, and the exact value was 9.97. Counting with integer division gives the logarithm rounded down, which books call the floor. The math review notes of Cornell University’s CS 211 course use exactly this reading: the floor of log2 n is the number of times n can be divided by 2 before reaching 1.

In PHP:

<?php

function countDivisions(int $number): int
{
    $divisions = 0;
    while ($number > 1) {
        $number = intdiv($number, 2);
        $divisions++;
    }
    return $divisions;
}

foreach ([8, 1000, 1024, 1000000] as $number) {
    echo $number, " ", countDivisions($number), "\n";
}

In C:

#include <stdio.h>

int count_divisions(int number)
{
    int divisions = 0;
    while (number > 1) {
        number = number / 2;
        divisions++;
    }
    return divisions;
}

int main(void)
{
    int numbers[] = {8, 1000, 1024, 1000000};

    for (int i = 0; i < 4; i++) {
        printf("%d %d\n", numbers[i], count_divisions(numbers[i]));
    }
    return 0;
}

Both versions show the same output as Python. Focus on the concept, not the language!

Why does the logarithm show up in algorithms?

Because every algorithm that throws away half of the problem at each step ends up with a number of steps tied to the logarithm of the size. Binary search is the most direct example. This program counts its steps in the worst case, when the value we’re looking for isn’t in the array:

def binary_search_steps(size):
    # worst case: the value we're looking for is greater than all the values in the array
    start = 0
    end = size - 1
    steps = 0
    while start <= end:
        middle = (start + end) // 2
        steps += 1
        start = middle + 1
    return steps


for size in [10, 1000, 1000000, 1000000000]:
    print(size, binary_search_steps(size))

Output:

10 4
1000 10
1000000 20
1000000000 30
Array sizeLooking item by item (worst case)Binary search (worst case)
1010 steps4 steps
1,0001,000 steps10 steps
1,000,0001,000,000 steps20 steps
1,000,000,0001,000,000,000 steps30 steps
Steps in the worst case: binary search grows with the logarithm of the size.
Chart comparing the steps of looking one by one, which reach 64, with those of splitting in half, which reach 6, in an array of 64 values
While one line climbs along with the size, the other barely leaves the ground.

The array got a thousand times bigger, and binary search needed only 10 more steps. Got it? That’s the power of the logarithm. The general rule, proven in Sedgewick and Wayne’s Algorithms book, from Princeton, is that binary search never takes more than log2 n + 1 steps.

Now you ask: what about the n × log n of sorting?

It’s the same idea, used several times. An algorithm like merge sort splits the array in half, then splits each half in half, and so on. The number of levels of this splitting is log2 n. At each level, all n values are gone through once. The total work comes to n × log2 n:

nn × log2 nn × n
82464
1,02410,2401,048,576
1,000,000about 20 million1 trillion
Why n × log n is so much better than n × n.

For one million values, the difference is 20 million operations against 1 trillion. That’s why the upcoming sorting articles insist so much on splitting the problem in half.

Which base: 2, 10 or e?

The base changes with the question. In computing, it’s almost always 2, because algorithms divide by 2. Base 10 counts orders of magnitude: the base-10 logarithm of 1,000 is 3, the number of zeros. And there’s a third base, the number e, which is about 2.718 and shows up in math and statistics formulas. The logarithm in this base is called the natural logarithm.

IMPORTANT: in Python, math.log with a single argument calculates the natural logarithm, not the base-10 or the base-2 one:

import math

print(math.log(100))
print(math.log10(100))
print(math.log(1000, 10))
print(math.log10(1000))

Output:

4.605170185988092
2.0
2.9999999999999996
3.0

Look at the third line. Passing base 10 as the second argument gave 2.9999999999999996 instead of 3. The Python documentation explains that, with two arguments, the result is calculated by dividing two logarithms, and points to math.log10 and math.log2 as the forms that are usually more accurate.

What are the most common mistakes with logarithms?

  • Mixing up logarithm and division. The base-2 logarithm of 16 isn’t 16 ÷ 2. It’s the number of times you can divide by 2 until you reach 1: four.
  • Forgetting the base. The logarithm of 1,000 is 3 in base 10 and almost 10 in base 2. Without the base, the question is incomplete.
  • Using the log function thinking it’s base 10. In Python, PHP and C, the log function with one argument calculates the natural logarithm: for 100, all three return 4.605.
  • Asking for the logarithm of zero or of a negative number. There’s no exponent that takes 2 to zero. In Python, math.log2(0) stops the program with ValueError: math domain error.

Now it’s your turn!

First on paper, without a calculator. What is the base-2 logarithm of 64? How many rounds does a knockout tournament with 128 teams have? And how many steps, in the worst case, does binary search take in an array with 2,000 values? Write down the three answers and only then check them with the programs in the article.

Then, on the computer: adapt the function that counts divisions so it also receives the base. With base 3, it should count how many times you can divide by 3. Test it with 81 and with 100. Try it on your own, without asking anyone for the ready-made answer, not even AI!

See you in the next article!

Stay confident!!!

Sources:

  • OpenStax (Rice University), College Algebra 2e with Corequisite Support. 6.3 Logarithmic Functions, with the logarithm as the exponent to which the base must be raised, the reading “log base 2 of 32 is 5”, and the common and natural logarithms.
  • OpenStax (Rice University), Intermediate Algebra 2e. Chapter 10 key terms, with the number e, about 2.718, and the natural logarithmic function, whose base is e.
  • Cornell University, CS 211. Math Review, with the integral binary logarithm: the floor of log2 n is the number of times n can be divided by 2 before reaching 1.
  • Pat Morin, Open Data Structures. 1.3 Mathematical Background, with the base-b logarithm as the value x that satisfies bx = k, the informal reading as a count of divisions by b, and the natural logarithm.
  • Virginia Tech, OpenDSA. Logarithms, with log n meaning log2 n in the analysis of algorithms, because they usually divide things in half.
  • Robert Sedgewick and Kevin Wayne, Algorithms, 4th edition (Princeton University). 3.1 Elementary Symbol Tables, with binary search using no more than lg N + 1 compares in the worst case.
  • Robert Sedgewick and Kevin Wayne, Algorithms, 4th edition (Princeton University). 2.2 Mergesort, with mergesort using between ½ N lg N and N lg N compares to sort an array of length N.
  • Python, official documentation. math: Mathematical functions, with the functions log, log2 and log10 and the two-argument log calculated as log(x)/log(base).
  • PHP, official manual. log, with the natural logarithm returned when no base is given.
  • GNU C Library, official manual. Exponentiation and Logarithms, with the log function, which computes the natural logarithm.
  • The examples were run on Python 3.13, PHP 8.3 and GCC 13.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).