(-5).rem(3) = -2 2.2 The Modulo Function ( .mod() ) Kotlin defines the Euclidean modulo $r$ such that: $$ a \equiv r \pmodb $$ and: $$ 0 \leq r < |b| $$ Sign rule: $r$ is always non-negative.
// BAD val r = a % b val correct = if (r < 0) r + b else r // GOOD val correct = a.mod(b) | Language | Operator/Function | Behavior | Sign of Result | | :--- | :--- | :--- | :--- | | Kotlin | % / .rem() | Truncated toward zero | Same as dividend | | Kotlin | .mod() | Floored (Euclidean) | Always non‑negative | | Python | % | Floored | Same as divisor | | Java | % | Truncated | Same as dividend | | Java | Math.floorMod() | Floored | Always non‑negative | | C / C++ | % | Truncated (impl‑defined pre‑C++11) | Same as dividend | | JavaScript | % | Truncated | Same as dividend | kotlin mod
Manually fixing a negative remainder:
// Verification of modulo property: // -5 ≡ 1 (mod 3) because -5 - 1 = -6, which is divisible by 3. which is divisible by 3.