CSES - Multiplication Table
Authors: Maggie Liu, Brad Ma
Explanation
We are asked to find the median of the numbers in an multiplication table, where is odd. If represents how many numbers in the multiplication table are less than or equal to , then the median will have at least numbers less than or equal to it. So, we want to find the smallest such that .
To find , 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 by the row number to find the number of columns where the number is less than or equal to . Taking the minimum of the number of columns and will tell us how many numbers in that row are less than or equal to , and summing over all rows will give us , which we store in the variable .
Using , we can do binary search until we find the median. If , we set to because works and is an upper bound for our answer. Otherwise, we set to because doesn't work, so numbers less than also won't work.
Implementation
Time Complexity:
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 medianwhile (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 = 1high = n**2# binary search to find the medianwhile low < high:mid = (low + high) // 2leq = 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!