{ }codelper
square rootif / elseP0424

Video call grid

A video call screen places the faces of n participants one per square cell of equal size, laid out like a grid.
The screen is split into c columns across and r rows down.
The number of columns c is the smallest positive integer such that c × c is at least n.
If c × (c - 1) is at least n, the number of rows r is c - 1; otherwise r is c.
Of the c × r cells on the screen, n hold a face and the remaining c × r - n hold none.
The first line gives the number of calls q, and each of the next q lines gives the number of participants n of one call.
For each call, print c, r and the number of cells without a face, in this order, separated by single spaces, on one line.
Print numbers without commas.

Input
1 ≤ q ≤ 1,000, 1 ≤ n ≤ 1,000,000,000 (all integers)
Output
q lines: for each call, c, r and the number of cells without a face
Example 1 · stdin
6
1
2
5
7
9
12
stdout
1 1 0
2 1 0
3 2 1
3 3 2
3 3 0
4 3 0
Example 2 · stdin
3
999950884
999950885
1000000000
stdout
31622 31622 0
31623 31622 31621
31623 31623 14129
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

The number of columns c is the square root of n rounded up.
The square root is Python math.sqrt, JS/TS Math.sqrt, Java Math.sqrt, C# Math.Sqrt, C sqrt (<math.h>), C++ std::sqrt (<cmath>) and Craykon Mathf.Sqrt, and all of them return a floating-point number (double).
Rounding up is Python math.ceil, JS/TS Math.ceil, Java Math.ceil, C# Math.Ceiling, C/C++ ceil and Craykon Mathf.Ceil.
In Java, C#, C and C++ the rounded-up value is still a double, so cast it with (int) to store it in an int.
In this problem's range (n ≤ 1,000,000,000) rounding up the double square root gives the exact answer.
The IEEE 754 square root operation is required to return the nearest double, so the root of a perfect square comes out as an exact integer, and the root of any other number is more than 0.00001 away from the nearest integer.
The Python solution gets c as math.isqrt(n - 1) + 1, which never goes through floating point (for n = 1 it is math.isqrt(0) + 1 = 1).
The rows are chosen with if-else: Python if c * (c - 1) >= n: … else:, C, C++, Java, C#, JS and TS if (c * (c - 1) >= n) { … } else { … }, Craykon if (…) { … } else { … }.
In Craykon a variable first assigned inside a block is not visible outside it, so the row variable is created before the block (for example rows = 0;).
The product c × r is at most 31,623 × 31,623 = 1,000,014,129, which fits in a 32-bit int (about 2.1 billion).
Trap one: rounding down.
Just converting to an integer, as in int(math.sqrt(n)) or (int)Math.sqrt(n), drops the fraction, so c is one too small whenever n is not a perfect square.
The 2 in example 1 becomes 1 1 -1 instead of 2 1 0.
Trap two: always adding 1 to the rounded-down value.
This is one too many for perfect squares: in example 1, 1 becomes 2 1 1 instead of 1 1 0, and 9 becomes 4 3 3 instead of 3 3 0.
Trap three: rounding to nearest.
Math.round or Mathf.Round goes down when the fraction is below 0.5.
The square root of 2, 1.41…, becomes 1 and the line is 1 1 -1.
Trap four: never choosing the rows and always using c.
The 5 in example 1 becomes 3 3 4 instead of 3 2 1.
Trap five: asking > instead of >=.
This misses the case where c × (c - 1) equals n exactly (2, 12), so 12 becomes 4 4 4 instead of 4 3 0.
Trap six: C# MathF.Sqrt.
It takes a float (about 7 significant digits), so the int n is converted to float without any error.
A float cannot hold every integer above 16,777,216 (2^24), and the square root comes back as a float too, so 999950885 in example 2 gives 31622 31622 -1 instead of 31623 31622 31621.

Pythonmain.py · 21 lines
import mathimport sys  def main():    data = sys.stdin.read().split()    q = int(data[0])    out = []    for i in range(1, q + 1):        n = int(data[i])        # c × c ≥ n인 가장 작은 c = n - 1의 정수 제곱근 + 1 (실수를 거치지 않는다)        c = math.isqrt(n - 1) + 1        if c * (c - 1) >= n:            r = c - 1        else:            r = c        out.append(f"{c} {r} {c * r - n}")    print("\n".join(out))  main()
JavaScriptmain.js · 15 lines
const [q, ...ns] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number); const out = [];for (let i = 0; i < q; i++) {  const n = ns[i];  const c = Math.ceil(Math.sqrt(n)); // c × c ≥ n인 가장 작은 c  let r;  if (c * (c - 1) >= n) {    r = c - 1;  } else {    r = c;  }  out.push(`${c} ${r} ${c * r - n}`);}console.log(out.join("\n"));
TypeScriptmain.ts · 16 lines
import { readFileSync } from "node:fs";const [q, ...ns]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number); const out: string[] = [];for (let i = 0; i < q; i++) {  const n: number = ns[i];  const c: number = Math.ceil(Math.sqrt(n)); // c × c ≥ n인 가장 작은 c  let r: number;  if (c * (c - 1) >= n) {    r = c - 1;  } else {    r = c;  }  out.push(`${c} ${r} ${c * r - n}`);}console.log(out.join("\n"));
JavaMain.java · 23 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int q = Integer.parseInt(br.readLine().trim());        StringBuilder sb = new StringBuilder();        for (int i = 0; i < q; i++) {            int n = Integer.parseInt(br.readLine().trim());            int c = (int) Math.ceil(Math.sqrt(n)); // Math.ceil은 double을 돌려준다            int r;            if (c * (c - 1) >= n) {                r = c - 1;            } else {                r = c;            }            sb.append(c).append(' ').append(r).append(' ').append(c * r - n).append('\n');        }        System.out.print(sb);    }}
C#Main.cs · 27 lines
using System;using System.Text; class Program{    static void Main()    {        int q = int.Parse(Console.ReadLine().Trim());        StringBuilder sb = new StringBuilder();        for (int i = 0; i < q; i++)        {            int n = int.Parse(Console.ReadLine().Trim());            int c = (int)Math.Ceiling(Math.Sqrt(n)); // Math.Sqrt는 double로 계산한다            int r;            if (c * (c - 1) >= n)            {                r = c - 1;            }            else            {                r = c;            }            sb.Append(c).Append(' ').Append(r).Append(' ').Append(c * r - n).Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 23 lines
#include <cmath>#include <iostream>using namespace std; int main() {    ios::sync_with_stdio(false);    cin.tie(nullptr);    int q;    cin >> q;    for (int i = 0; i < q; i++) {        int n;        cin >> n;        int c = static_cast<int>(ceil(sqrt(static_cast<double>(n)))); // c × c ≥ n인 가장 작은 c        int r;        if (c * (c - 1) >= n) {            r = c - 1;        } else {            r = c;        }        cout << c << ' ' << r << ' ' << c * r - n << '\n';    }    return 0;}
Cmain.c · 20 lines
#include <math.h>#include <stdio.h> int main(void) {    int q;    if (scanf("%d", &q) != 1) return 1;    for (int i = 0; i < q; i++) {        int n;        if (scanf("%d", &n) != 1) return 1;        int c = (int)ceil(sqrt((double)n)); /* c × c ≥ n인 가장 작은 c */        int r;        if (c * (c - 1) >= n) {            r = c - 1;        } else {            r = c;        }        printf("%d %d %d\n", c, r, c * r - n);    }    return 0;}
Craykonmain.cray · 16 lines
회의수 = Console.ReadLine().ToNumber();for (i = 0; i < 회의수; i++){    n = Console.ReadLine().ToNumber();    열 = Mathf.Ceil(Mathf.Sqrt(n)); // 열 × 열 ≥ n인 가장 작은 열    행 = 0; // 블록 안에서 처음 넣은 변수는 블록 밖에서 안 보여서 먼저 만들어 둔다    if (열 * (열 - 1) >= n)    {        행 = 열 - 1;    }    else    {        행 = 열;    }    Console.WriteLine(열 + " " + 행 + " " + (열 * 행 - n));}