Alex Rivera | Logout

What's the difference between “mod” and “remainder”?

Asked 2012-12-03T12:45:42.927
228

My friend said that there are differences between "mod" and "remainder".

If so, what are those differences in C and C++? Does '%' mean either "mod" or "rem" in C?

Edit
Report

1 Answer

209

There is a difference between modulus (Euclidean division) and remainder (C's % operator). For example:

-21 mod 4 is 3 because -21 + 4 x 6 is 3.

But -21 divided by 4 with truncation towards 0 (as C's / operator)
gives -5 with a remainder (C -21 % 4) of -1.

For positive values, there is no difference between Euclidean and truncating division.

See https://en.wikipedia.org/wiki/Euclidean_division#Other_intervals_for_the_remainder - C's choice of truncating the remainder towards 0 (required since C99) forces a negative remainder range for negative quotients. Even in C89, when Euclidean division was allowed by the standard for /

If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

(-21/4) * 4 + (-21%4) == -21; C99 and later require (-5) * 4 + (-1), not Euclidean -6 and 3.

answered 2012-12-03T12:54:58.110

Your Answer