0

A modulo operation a%b returns the remainder for a/b but for negative numbers it does not do so.

#include <stdio.h>

int main(void) {
  int n=-4;
  printf("%d\n",n%3);
  return 0;
}

It should return 2 as 3*(-2)=-6 is just smaller than -4 and a multiple of 3 but the output is -1. Why is it treating (-a) mod b same as -(a mod b)

  • Because that's how mods work? `-4 % 3 === -1`, not `-2`. – elixenide May 12 '15 at 19:12
  • If you try to divide -4 into 3 parts, you get 3 pieces of size -1 and one piece of size -1 that you couldn't divide. (That said, it turns out to be more useful if the result is +2 and -4/3 results in -2, but we're stuck with it returning -1.) – user2357112 May 12 '15 at 19:13
  • Notice that "-4 minus -6" is equal to "-4 plus +6" equals "+2" not "-2." Nope, the rules of mathematics always apply: just as "+4 modulo 3" is equal to "+1," "-4 modulo 3" is equal to "-1." – Mike Robinson May 12 '15 at 19:31

2 Answers2

5

As a general rule, the modulo and division should satisfy the equation

b * (a/b) + a%b == a

For positive numbers, it is obvious that this means that a%b must be a positive number. But if a/b is negative, then the result is rounded towards zero.

So take for instance a = -4, b = 3. We know that a/b = -1.3333, which rounded towards zero becomes a/b == -1. From the equation above, we have that b * (-1) + a%b == a. If we insert a and b, we get -3 + a%b == -4, and we see that a%b must be -1.

Frxstrem
  • 38,761
  • 9
  • 79
  • 119
4

Your suffering stems from embracing the illusion that % is a "modulo" operator. In truth, it is a remainder operator (C11 §6.5.5):

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder

Reject the illusion and accept the truth, and the behavior of the operator will become clear (Ibid.):

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

In your case, a/b is -4/3, which is -1, hence representable. So a%b satisfies:

(a/b)*b + a%b =  a
(-1)*3  + a%b = -4
  -3    + a%b = -4
          a%b = -1
Stephen Canon
  • 103,815
  • 19
  • 183
  • 269
  • Odd ... I thought that the mathematical definition of modulo *was* "the remainder." – Mike Robinson May 12 '15 at 19:33
  • @MikeRobinson: In computing it is. But this confuses people who expect the remainder `a%b` to be "a modulo b" in the casual mathematical sense (which, depending on who you ask, is either strictly positive or matches the sign of `b`, not `a`). – Stephen Canon May 12 '15 at 19:38
  • The issue here is that with C / C++, integer division rounds towards zero so the remainder is zero or has the same sign as the dividend, while in mathematics and some other programming languages, integer division rounds towards negative infinity, so the remainder is zero or has the same sign as the divisor. – rcgldr May 12 '15 at 20:07