1406. Two Answers for the Same Division
For each query print four integers on one line: the floor quotient of
a by b, its matching remainder, the truncating quotient, and its
matching remainder.
A quotient q and remainder r always satisfy a = q * b + r. There are two
standard ways to choose q when the division is inexact and the result is
negative, and this problem asks for both so the difference is impossible to
miss.
a = 7, b = 2 -> 3 1 3 1
a = -7, b = 2 -> -4 1 -3 -1
a = 7, b = -2 -> -4 -1 -3 1
a = -7, b = -2 -> 3 -1 3 -1
## What most people try first
Write a / b and a % b and hand in whatever the language produces. That
answers half the question in C, C++, Java and JavaScript, and the other half
in Python, which is exactly why this problem exists.
## The two definitions
Floor division rounds the quotient toward negative infinity. Its remainder
is a - floor(a/b) * b, which always carries the sign of `b` and lies in
[0, |b|) when b is positive.
Truncating division rounds the quotient toward zero. Its remainder is
a - trunc(a/b) * b, which always carries the sign of `a`.
The two agree whenever the division is exact, and whenever a and b have the
same sign. They differ by exactly one in the quotient otherwise.
a = -7, b = 2
floor: -7 = (-4) * 2 + 1 quotient -4, remainder 1
truncating: -7 = (-3) * 2 + (-1) quotient -3, remainder -1
## Why one correction step is enough
Suppose the division is inexact and the signs differ, so the true quotient
a/b is strictly negative and not an integer. Truncation rounds it up
toward zero, floor rounds it down, and since the true value lies strictly
between two consecutive integers those two roundings are adjacent. So
floor = trunc - 1, and in every other case they are equal. That is the whole
proof, and it is why
q = a / b; if (a % b != 0 && ((a < 0) != (b < 0))) q--;
is correct rather than merely plausible. In Python the roles swap: // already
floors, and truncation has to be built from abs.
## Overflow
|a| and |b| reach 10^18, so both need 64 bits: a signed 32-bit integer
stops at 2147483647 and cannot even hold the input, which is why a 32-bit
build reports -495539542 where the truth is 333333333333333333. The products
q * b are bounded by |a| + |b| in magnitude, because q * b is within
|b| of a, so they also fit 64 bits and nothing overflows after the read.
In JavaScript 10^18 is past 2^53, so every value is a BigInt, and BigInt
division truncates toward zero just as C does.
## Cost
O(1) per query.
Constraints - `1 ≤ q ≤ 1000` - `-1000000000000000000 ≤ a ≤ 1000000000000000000` - `-1000000000000000000 ≤ b ≤ 1000000000000000000` - `b` is not 0
Input
The first line contains q.
Each of the next q lines contains a and b, with b never 0.
Output
For each query print the floor quotient, the floor remainder, the truncating quotient and the truncating remainder, separated by single spaces, one query per line.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.