5

In C the following code ...

#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<stdlib.h>

int main() {
   int result = (-12) % (10);
   printf("-12 mod 10 = %d\n",result);
   return 0;
}

gives this output

> gcc modTest.c
> ./a.out
-12 mod 10 = -2

But according to this mod calculator -12 mod 10 = 8

In Python ...

> python
Python 3.3.0 (default, Mar 26 2013, 09:56:30)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> (-12) % (10)
8

What is going on in C that produces -2 instead of 8?

SA610
  • 55
  • 1
  • 6

3 Answers3

4

The C11 standard says:

6.5.5:6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.(105) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined.

with footnote 105:

105) This is often called ‘‘truncation toward zero’’.

Another way to define division is to round towards -oo. This is called Euclidean division. Python appears to use yet another definition, according to user3307862's link.

The % operator, properly called “remainder”, is defined with respect to the corresponding division, so it either is always in [0..b) or in (-b..b) depending on the definition of /.

Community
  • 1
  • 1
Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
1

In modulo 10, -2 is equivalent to 8. They're just two different representations of the same thing.

pattivacek
  • 5,617
  • 5
  • 48
  • 62
0

C is doing correct math. You can check it on the regular calculator.

Python behavior is explained here:

negative numbers modulo in python

Community
  • 1
  • 1
  • 1
    Mathematicians usually prefer Euclidean division, and would not call “correct” the division as defined in C, which is just as quirky to them as the definition in Python. – Pascal Cuoq Feb 24 '14 at 15:45
  • The "modulo arithmetic" I learned long ago simply defines `x%y` as the _remainder_ after `x/y`. -12/10 gives me -1 as the quotient and -2 as the remainder. So where is C (and by extension, computer hardware integer division) going wrong? I can _understand_ a result of 8, but I would _expect_ -2. – Phil Perry Feb 24 '14 at 15:53
  • 1
    No one is "going wrong". There are simply several ways in which to define the quotient `q` and remainder `r` so that the division `n/d` satisfies `n = d*q + r`, and different languages choose to implement different definitions. – chepner Feb 24 '14 at 16:19