CSES - Multiplication Table

Authors: Maggie Liu, Brad Ma

Table of Contents

ExplanationImplementation

Explanation

We are asked to find the median of the numbers in an n×nn \times n multiplication table, where nn is odd. If f(x)f(x) represents how many numbers in the multiplication table are less than or equal to xx, then the median will have at least n2+12\frac{n^2 + 1}{2} numbers less than or equal to it. So, we want to find the smallest xx such that f(x)n2+12f(x) \geq \frac{n^2 + 1}{2}.

To find f(x)f(x), we can loop through each row of the table. Since the numbers in a row are the column number multiplied by the row number, we can divide xx by the row number to find the number of columns where the number is less than or equal to xx. Taking the minimum of the number of columns and nn will tell us how many numbers in that row are less than or equal to xx, and summing over all rows will give us f(x)f(x), which we store in the variable leq\texttt{leq}.

Using leq\texttt{leq}, we can do binary search until we find the median. If leqn2+12\texttt{leq} \geq \frac{n^2 + 1}{2}, we set high\texttt{high} to mid\texttt{mid} because mid\texttt{mid} works and is an upper bound for our answer. Otherwise, we set low\texttt{low} to mid+1\texttt{mid} + 1 because mid\texttt{mid} doesn't work, so numbers less than mid\texttt{mid} also won't work.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N\log N)

C++

#include <iostream>
using namespace std;
int main() {
long long n;
cin >> n;
long long low = 1, high = n * n, mid, leq;
// binary search to get the median
while (low < high) {

Java

import java.io.*;
import java.util.StringTokenizer;
public class MultiplicationTable {
public static void main(String[] args) {
Kattio io = new Kattio();
long n = io.nextInt();
long low = 1, high = n * n, mid, leq;
// binary search to find the median

Python

n = int(input())
low = 1
high = n**2
# binary search to find the median
while low < high:
mid = (low + high) // 2
leq = 0

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!