Sign in

Modular Subtraction, Always Non-Negative

core

Implement long long sub_mod(long long a, long long b, long long m) (m > 0) computing (a - b) mod m as a value in the range 0 to m - 1 inclusive, using the exact expression ((a - b) % m + m) % m. This matters because in both C++ and JavaScript % returns a result with the same sign as the dividend (it truncates toward zero rather than flooring), so a plain (a - b) % m is negative whenever b > a and (a - b) is not a multiple of m; sub_mod must never return a negative value. The normalisation is required in both languages, unchanged. Both a and b can be arbitrarily larger than m in either direction, and either can exceed the other.

Example: sub_mod(3, 5, 4) returns 2. Naively, (3 - 5) % 4 is -2 % 4, which C++ and JavaScript both evaluate to -2 (not 2) since the result takes the sign of the dividend; adding m and re-modding fixes it: (-2 + 4) % 4 = 2.

Input format: each test in tests/*.in is laid out as:

  • Line 1: q, the number of queries.
  • Next q lines: a b m, one sub_mod(a, b, m) query per line.

Test 04.in reads:

2
0 0 1
2 10 3

This is two queries: 0 0 1 (everything is 0 mod 1) and 2 10 3, where 2 - 10 = -8 must come back as 1, not -2.

Where you'll use it:

✦ Solution & editorial unlock with the pass.

Loading...