In Ada, what does the expression 5 mod (-3) evaluate to, and how does that differ from 5 rem (-3)?
In Ada, what does the expression 5 mod (-3) evaluate to, and how does that differ from 5 rem (-3)?
In Ada, what does the expression 5 mod (-3) evaluate to, and how does that differ from 5 rem (-3)?
5 mod (-3) evaluates to -1, while 5 rem (-3) evaluates to 2.
The difference comes down to which operand's sign the result follows. Ada defines both operators in the Reference Manual section 4.5.5 (Multiplying Operators):
rem satisfies A = (A/B)*B + (A rem B), and (A rem B) takes the sign of the left operand A (the dividend), with an absolute value less than abs B. Ada's integer / truncates toward zero, so 5/(-3) = -1, giving 5 rem (-3) = 5 - (-1)*(-3) = 5 - 3 = 2 (positive, like the dividend 5).
mod satisfies A = B*N + (A mod B) for some integer N, and (A mod B) takes the sign of the right operand B (the divisor), with an absolute value less than abs B. For 5 mod (-3) the result must be negative and < 3 in magnitude: with N = -2, (-3)*(-2) + (-1) = 6 - 1 = 5, so 5 mod (-3) = -1.
Put simply:
rem -> sign of the dividend (first operand)mod -> sign of the divisor (second operand)When both operands are positive the two operators give identical results; they diverge only when a negative operand is involved. (If the right operand is 0, both raise Constraint_Error.)
This matches the worked examples in the RM table, e.g. 11 rem (-5) = 1 but 11 mod (-5) = -4 — the same dividend-positive / divisor-negative shape as the question.
Quick check in code:
with Ada.Text_IO; use Ada.Text_IO;
procedure Demo is
begin
Put_Line (Integer'Image (5 mod (-3))); -- -1
Put_Line (Integer'Image (5 rem (-3))); -- 2
end Demo;
Sources: