A Rust ledger splits signed `i64` adjustments across holders; what do `/` and `%` do with negative amounts, zero holders and `i64::MIN / -1` in a release build?
answer
- toward zero, not toward minus infinity
- the remainder follows the dividend
- two panics no profile disables
- euclid for a non-negative remainder
basics
~20 sInteger / rounds toward zero and % takes the dividend's sign, so -1001 split four ways is -250 remainder -1. Dividing by zero and i64::MIN / -1 panic in every build, release included; checked_div and checked_rem return None instead.
solid answer
~50 sRust's integer division truncates toward zero, so `-7 / 2` is `-3`, and `%` is defined from that truncation, so `-7 % 2` is `-1`: the remainder has the dividend's sign. For a ledger, `-1001 / 4` gives shares of -250 and a leftover of -1 cent that must still be booked. If you need a remainder that is never negative, as for bucketing or ring-buffer indices, use `rem_euclid` (and `div_euclid`), which give `-4` and `1` for `(-7, 2)`. Two division cases panic regardless of the profile: dividing by zero (`attempt to divide by zero`) and `i64::MIN / -1`, whose true result does not fit (`attempt to divide with overflow`); the Reference keeps that check even with overflow checks disabled. With holders coming from input, `checked_div` and `checked_rem` turn both into `None`. Floats differ: `1.0 / 0.0` is infinity, not a panic.
code
rust · 17 linesuse std::hint::black_box;
fn share(adjustment: i64, holders: i64) -> Option<(i64, i64)> {
let each = adjustment.checked_div(holders)?;
let leftover = adjustment.checked_rem(holders)?;
Some((each, leftover))
}
fn main() {
println!("{} {}", -7 / 2, -7 % 2); // -3 -1
println!("{} {}", (-7i64).div_euclid(2), (-7i64).rem_euclid(2)); // -4 1
println!("{:?}", share(-1001, 4)); // Some((-250, -1))
println!("{:?}", share(500, 0)); // None
println!("{:?}", share(i64::MIN, -1)); // None
let n = black_box(i64::MIN);
println!("{}", n / black_box(-1)); // panics, even with -O
}go deeper
Recall that integer division drops the fraction toward zero and that dividing an integer by zero panics.
Explain that % follows the dividend's sign, -7 % 2 being -1, and when rem_euclid and div_euclid give the answer modular code needs.
Name the two release-mode panics, zero divisor and MIN / -1, as denial-of-service paths when divisors come from input, and route them through checked_div and checked_rem.
Decide how a team handles remainders that must be booked, such as leftover cents, so splitting rules are explicit and identical for credits and refunds.
## Truncating division Integer division in Rust **rounds toward zero**. For positive operands that matches the school rule; for negative ones it does not round down: | Expression | Result | Note | |---|---|---| | `7 / 2` | `3` | | | `-7 / 2` | `-3` | toward zero, not -4 | | `7 / -2` | `-3` | | | `-7 % 2` | `-1` | remainder takes the dividend's sign | | `7 % -2` | `1` | | | `(-7i64).div_euclid(2)` | `-4` | Euclidean quotient | | `(-7i64).rem_euclid(2)` | `1` | never negative | The **remainder** operator `%` is defined from truncating division, so `a == (a / b) * b + a % b` holds whenever the division is defined, and `a % b` has the sign of `a`. The **Euclidean** methods instead guarantee `0 <= r < |b|` for the remainder, which is what modular indexing needs. ## Splitting a ledger adjustment A signed `i64` adjustment in cents, split across holders: - `-1001 / 4` is `-250` per holder and `-1001 % 4` is `-1` left over. The leftover must be assigned somewhere, or the ledger no longer balances. - `1001 / 4` is `250` with `1` left over: the same magnitude, mirrored, because truncation is symmetric around zero. A rule written as "the remainder goes to the first holder" works for both signs with `/` and `%` precisely because the remainder's sign follows the amount. Code that assumed a non-negative remainder, for example to pick an index, breaks on refunds. ## The two panics no build profile removes Most integer overflow panics only in debug builds and wraps in a default release build. **Division is the exception**: 1. **Division by zero.** `x / 0` panics with `attempt to divide by zero`, and `x % 0` with `attempt to calculate the remainder with a divisor of zero`, in every build. There is no wrapped answer to fall back on. 2. **`MIN / -1`.** For a signed type, `i64::MIN / -1` would be `i64::MAX + 1`, which does not fit. The Reference states that this check occurs even when overflow checks are disabled, "for legacy reasons"; the panic message is `attempt to divide with overflow`. `i64::MIN % -1` is checked the same way. So a release binary that divides by a holder count taken from a request can be crashed by a request with zero holders, and one that divides by a signed value from input can be crashed by `-1` paired with `i64::MIN`. ## The checked forms - `adjustment.checked_div(holders)` returns `None` when `holders` is 0 **or** the division overflows. - `adjustment.checked_rem(holders)` does the same for the remainder. - `wrapping_div` and `wrapping_rem` define `MIN / -1` as `MIN` and `MIN % -1` as `0`, but still panic on a zero divisor. - The strict division methods panic on both cases; they are for invariants, not for input. ```rust fn share(adjustment: i64, holders: i64) -> Option<(i64, i64)> { let each = adjustment.checked_div(holders)?; let leftover = adjustment.checked_rem(holders)?; Some((each, leftover)) } ``` `share(-1001, 4)` is `Some((-250, -1))`, `share(500, 0)` is `None` and `share(i64::MIN, -1)` is `None`. ## Rounding policy is a business rule Truncation toward zero is a language rule, not an accounting one. A ledger that splits a refund needs to decide, and write down, where leftover cents go: - **Largest share first**: give the remainder, one cent at a time, to the first holders; with truncating `/` and `%` this works for credits and refunds alike because the remainder carries the amount's sign. - **Floor toward minus infinity**: if every share must round down regardless of sign, `div_euclid` gives the floor for a positive divisor, with `rem_euclid` as the non-negative leftover. - **Banker's rounding or a currency's own rule**: implement it explicitly on integers; never move the amount into `f64` to use `round()`. Whatever the choice, the invariant to test is that the shares plus the leftover add back to the original amount. ## Floats behave differently Floating-point division never panics. `1.0 / 0.0` is `inf`, `-1.0 / 0.0` is `-inf`, and `0.0 / 0.0` is NaN, following IEEE 754. Float `%` also takes the dividend's sign: `-7.5 % 2.0` is `-1.5`. A ledger that moved amounts into `f64` to avoid the panic would trade a crash for a silent infinity, which is worse. ## What interviewers listen for - That `-7 / 2` is `-3` and why, without guessing `-4`. - That `%` is a remainder, not a mathematical modulus, and `rem_euclid` is the modulus. - That division by zero and `MIN / -1` panic in release, unlike `+` and `*`. - That untrusted divisors go through `checked_div` and `checked_rem`.
- Why does `(head + offset) % len` panic as an index on a ring buffer when `offset` is negative, and what replaces it?With signed operands, `%` returns a negative remainder for a negative dividend, so the index can be -1, and converting it to `usize` either fails or wraps to a huge value that is out of bounds. `(head + offset).rem_euclid(len)` always returns a value in `0..len` for a positive `len`.
- Does `wrapping_div` make division by zero safe?No. `wrapping_div` only defines the overflow case, so `i64::MIN.wrapping_div(-1)` is `i64::MIN`; a zero divisor still panics. Only `checked_div` (and `checked_rem`) turns a zero divisor into a value, `None`.
- -7 / 2 is -4 in Rust because division rounds down.
- The % operator always returns a non-negative result.
- Release builds wrap i64::MIN / -1 like any other overflow.
- Integer division by zero returns 0 in release builds.
- wrapping_div makes division by zero safe.
- Float division by zero panics just like integer division.