The two conventions, the conversion formula, the congruence perspective, the pitfalls — these reduce to a small set of practical decisions a reader actually faces when writing or reading code with negative inputs. The table below collects those situations and the matching action, with a concrete example or note for each.
| Situation |
What to do |
Example or note |
| Need the canonical mathematical remainder (in {0, …, n − 1}) |
apply ((a % n) + n) % n — works in any language regardless of the native convention |
JavaScript: (−7) % 3 = −1 → ((−1) + 3) % 3 = 2 |
| Working with congruence relations only |
either convention is fine — the two results differ by a multiple of n and represent the same class |
−7 ≡ −1 ≡ 2 (mod 3) |
| Code may run in multiple languages |
apply ((a % n) + n) % n uniformly — the universal idiom is convention-agnostic |
avoids Python-vs-JavaScript divergence on negative inputs |
| Indexing into an array with wrap-around |
force non-negative with ((i % n) + n) % n — never trust raw % for this |
(−1) % n returns n − 1 in Python (OK) but −1 in JavaScript (invalid index) |
| Negative divisor (n < 0) |
avoid — replace n with |n| and handle any sign logic explicitly |
behavior is unpredictable across languages and conventions |