284

In a C program I was trying the below operations (Just to check the behavior)

 x = 5 % (-3);
 y = (-5) % (3);
 z = (-5) % (-3); 

printf("%d ,%d ,%d", x, y, z); 

It gave me output as (2, -2 , -2) in gcc. I was expecting a positive result every time. Can a modulus be negative? Can anybody explain this behavior?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Alva
  • 2,882
  • 3
  • 14
  • 8
  • Possible duplicate of http://stackoverflow.com/questions/4003232/how-to-code-a-modulo-operator-in-c-c-obj-c-that-handles-negative-numbers – Mushahid Hussain Jul 30 '12 at 11:41
  • 1
    possible duplicate of [Modulo operator with negative values](http://stackoverflow.com/questions/7594508/modulo-operator-with-negative-values) – sugavaneshb Feb 08 '15 at 08:46
  • There are two different interpretations of modulus https://torstencurdt.com/tech/posts/modulo-of-negative-numbers/ – tcurdt Feb 01 '22 at 12:26

13 Answers13

229

C99 requires that when a/b is representable:

(a/b) * b + a%b shall equal a

This makes sense, logically. Right?

Let's see what this leads to:


Example A. 5/(-3) is -1

=> (-1) * (-3) + 5%(-3) = 5

This can only happen if 5%(-3) is 2.


Example B. (-5)/3 is -1

=> (-1) * 3 + (-5)%3 = -5

This can only happen if (-5)%3 is -2

ArjunShankar
  • 23,020
  • 5
  • 61
  • 83
  • 1
    Should the compiler be smart enough and detect that an unsigned modulo another unsigned is always positive? Currently (well, GCC 5.2) the compiler seems to think that "%" returns an "int" in this case, rather than "unsigned" even when both operands are uint32_t or bigger. – Frederick Nord Sep 24 '16 at 14:56
  • @FrederickNord Do you have an example to show [that behavior](http://stackoverflow.com/questions/11720656/modulo-operation-with-negative-numbers#comment66655578_11720841)? – chux - Reinstate Monica Feb 24 '17 at 16:16
  • 17
    Understand that what you describe is the usual int(a/b) (truncate) description of mod. But it is also possible that the rule is floor(a/b) (Knuth). In the Knuth case `-5/3` is `-2` and the mod becomes 1. In short: one module has a sign that follows the dividend sign (truncate), the other module has a sign that follows the divisor sign (Knuth). –  May 27 '18 at 09:36
  • 3
    This is a case of the C standard being exactly not what I want. I have never wanted truncate to zero or negative modulo numbers, but often want the opposite and need to work around C. – Joe Aug 06 '18 at 22:27
  • I don't understand, why should a + a%b = a "logically"? – Nick Sep 25 '21 at 12:44
  • @Nick where is that written? – ArjunShankar Nov 30 '21 at 17:50
  • 1
    @Nick the `a/b` in the expression `(a/b) * b + a%b` above is integer division, so `(a/b) * b` is not equal to `a` unless `a` is divisible by `b`. – Laurence Gonsalves Dec 17 '21 at 17:51
  • This just restates the question in terms of the integer value of a negative quotient. If it were defined as floor(a/b), then the equivalence would only work if the result of the `%` operator were always nonnegative. C instead does integer conversion by rounding toward 0, which is why the equivalence requires `%` to return negative values in some cases. – Mark Reed Nov 18 '22 at 16:48
225

The % operator in C is not the modulo operator but the remainder operator.

Modulo and remainder operators differ with respect to negative values.

With a remainder operator, the sign of the result is the same as the sign of the dividend (numerator) while with a modulo operator the sign of the result is the same as the divisor (denominator).

C defines the % operation for a % b as:

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

with / the integer division with truncation towards 0. That's the truncation that is done towards 0 (and not towards negative inifinity) that defines the % as a remainder operator rather than a modulo operator.

APerson
  • 8,140
  • 8
  • 35
  • 49
ouah
  • 142,963
  • 15
  • 272
  • 331
  • 20
    [Remainder is the result of modulo operation](https://en.wikipedia.org/wiki/Remainder) by definition. There should be no such thing as remainder operator because there is no such thing as remainder operation, it's called modulo. – gronostaj Jun 27 '15 at 20:49
  • 75
    @gronostaj not in CS. Look at higher level languages like Haskell or Scheme that both define two different operators (`remainder` and `modulo` in Scheme, `rem` and `mod` in Haskell). These operators specifications differ on these languages on how the division is done: truncation towards 0 or toward negative infinity. By the way the C Standard never calls the `%` the *modulo operator*, they just name it the *% operator*. – ouah Dec 21 '15 at 16:55
  • 4
    Not to be confused with the `remainder` _function_ in C, which implements IEEE remainder with round-towards-nearest semantics in the division – Eric Sep 18 '17 at 02:11
  • @gronostaj The link that you provided specifically makes the distinction between *least positive remainder*, and *least absolute remainder* which is obviously not always positive. It gives `-2` as the least absolute remainder of `43 / 5` (since `43 = 9 * 5 - 2`). The CS definition is yet again different. But it is worth pointing out that just because we learned something when we were 10 years old, there still might be some subtleties. Try `round(2.5)` in Python, for instance. It's 2, not 3. And that is mathematically correct, to prevent bias in statistical moments. – Mike Williamson Feb 18 '21 at 17:25
94

Based on the C99 Specification: a == (a / b) * b + a % b

We can write a function to calculate (a % b) == a - (a / b) * b!

int remainder(int a, int b)
{
    return a - (a / b) * b;
}

For modulo operation, we can have the following function (assuming b > 0)

int mod(int a, int b)
{
    int r = a % b;
    return r < 0 ? r + b : r;
}

My conclusion is that a % b in C is a remainder operation and NOT a modulo operation.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
dewang
  • 961
  • 6
  • 2
  • 5
    This does not give positive results when `b` is negative (and in fact for `r` and `b` both negative it gives results less than `-b`). To ensure positive results for all inputs you could use `r + abs(b)` or to match `b`s sign you could change the condition to `r*b < 0` instead. – Martin Ender Sep 20 '16 at 11:42
  • 1
    @MartinEnder `r + abs(b)` is UB when `b == INT_MIN`. – chux - Reinstate Monica Sep 27 '18 at 04:20
85

I don't think there isn't any need to check if the number is negative.

A simple function to find the positive modulo would be this -

Edit: Assuming N > 0 and N + N - 1 <= INT_MAX

int modulo(int x,int N){
    return (x % N + N) %N;
}

This will work for both positive and negative values of x.

Original P.S: also as pointed out by @chux, If your x and N may reach something like INT_MAX-1 and INT_MAX respectively, just replace int with long long int.

And If they are crossing limits of long long as well (i.e. near LLONG_MAX), then you shall handle positive and negative cases separately as described in other answers here.

Community
  • 1
  • 1
Udayraj Deshmukh
  • 1,814
  • 1
  • 14
  • 22
  • 3
    Note that when `N < 0`, the result may be negative as in `modulo(7, -3) --> -2`. Also `x % N + N` can overflow `int` math which is undefined behavior. e.g. `modulo(INT_MAX - 1,INT_MAX)` might result in -3. – chux - Reinstate Monica Sep 27 '18 at 04:17
  • Yes, in that case you may simply use `long long int`, or handle the negative case separately (at the cost of losing simplicity). – Udayraj Deshmukh Oct 07 '18 at 14:08
13

Can a modulus be negative?

% can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.

 // a % b
 7 %  3 -->  1  
 7 % -3 -->  1  
-7 %  3 --> -1  
-7 % -3 --> -1  

The modulo OP wanted is a classic Euclidean modulo, not %.

I was expecting a positive result every time.

To perform a Euclidean modulo that is well defined whenever a/b is defined, a,b are of any sign and the result is never negative:

int modulo_Euclidean(int a, int b) {
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

modulo_Euclidean( 7,  3) -->  1  
modulo_Euclidean( 7, -3) -->  1  
modulo_Euclidean(-7,  3) -->  2  
modulo_Euclidean(-7, -3) -->  2   
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
10

The other answers have explained in C99 or later, division of integers involving negative operands always truncate towards zero.

Note that, in C89, whether the result round upward or downward is implementation-defined. Because (a/b) * b + a%b equals a in all standards, the result of % involving negative operands is also implementation-defined in C89.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
5

According to C99 standard, section 6.5.5 Multiplicative operators, the following is required:

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

Conclusion

The sign of the result of a remainder operation, according to C99, is the same as the dividend's one.

Let's see some examples (dividend / divisor):

When only dividend is negative

(-3 / 2) * 2  +  -3 % 2 = -3

(-3 / 2) * 2 = -2

(-3 % 2) must be -1

When only divisor is negative

(3 / -2) * -2  +  3 % -2 = 3

(3 / -2) * -2 = 2

(3 % -2) must be 1

When both divisor and dividend are negative

(-3 / -2) * -2  +  -3 % -2 = -3

(-3 / -2) * -2 = -2

(-3 % -2) must be -1

6.5.5 Multiplicative operators

Syntax

  1. multiplicative-expression:
    • cast-expression
    • multiplicative-expression * cast-expression
    • multiplicative-expression / cast-expression
    • multiplicative-expression % cast-expression

Constraints

  1. Each of the operands shall have arithmetic type. The operands of the % operator shall have integer type.

Semantics

  1. The usual arithmetic conversions are performed on the operands.

  2. The result of the binary * operator is the product of the operands.

  3. 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. In both operations, if the value of the second operand is zero, the behavior is undefined.

  4. When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded [1]. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

[1]: This is often called "truncation toward zero".

psqli
  • 588
  • 6
  • 11
2

The result of Modulo operation depends on the sign of numerator, and thus you're getting -2 for y and z

Here's the reference

http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_14.html

Integer Division

This section describes functions for performing integer division. These functions are redundant in the GNU C library, since in GNU C the '/' operator always rounds towards zero. But in other C implementations, '/' may round differently with negative arguments. div and ldiv are useful because they specify how to round the quotient: towards zero. The remainder has the same sign as the numerator.

user207421
  • 305,947
  • 44
  • 307
  • 483
Kartik Anand
  • 4,513
  • 5
  • 41
  • 72
  • 5
    You are referring to a text about ANSI C. This is a fairly old norm of C. Not sure if the text is correct with regard to ANSI C, but definitely not with regard to C99. In C99 §6.5.5 integer division is defined to always truncate towards zero. – Palec Feb 05 '14 at 20:36
2

In Mathematics, where these conventions stem from, there is no assertion that modulo arithmetic should yield a positive result.

Eg.

1 mod 5 = 1, but it can also equal -4. That is, 1/5 yields a remainder 1 from 0 or -4 from 5. (Both factors of 5)

Similarly, -1 mod 5 = -1, but it can also equal 4. That is, -1/5 yields a remainder -1 from 0 or 4 from -5. (Both factors of 5)

For further reading look into equivalence classes in Mathematics.

DarkPurple141
  • 280
  • 2
  • 9
  • Equivalence class is a different concept and modulo is defined in a very strict way. Let's say we have two integer numbers `a` and `b`, `b <> 0`. According to the Euclidean division theorem there exists exactly one pair of integers `m`, `r` where `a = m * b + r` and `0 <= r < abs( b )` . The said `r` is the result of the (mathematical) modulo operation and by definition is non negative. More reading and further links on Wikipedia: https://en.wikipedia.org/wiki/Euclidean_division – Ister May 09 '18 at 06:54
  • That isn't true. `1 mod 5` is always 1. `-4 mod 5` might be 1 too, but they are different things. – FelipeC Jun 05 '19 at 07:35
1

Modulus operator gives the remainder. Modulus operator in c usually takes the sign of the numerator

  1. x = 5 % (-3) - here numerator is positive hence it results in 2
  2. y = (-5) % (3) - here numerator is negative hence it results -2
  3. z = (-5) % (-3) - here numerator is negative hence it results -2

Also modulus(remainder) operator can only be used with integer type and cannot be used with floating point.

Kavya
  • 11
  • 2
1

I believe it's more useful to think of mod as it's defined in abstract arithmetic; not as an operation, but as a whole different class of arithmetic, with different elements, and different operators. That means addition in mod 3 is not the same as the "normal" addition; that is; integer addition.

So when you do:

5 % -3

You are trying to map the integer 5 to an element in the set of mod -3. These are the elements of mod -3:

{ 0, -2, -1 }

So:

0 => 0, 1 => -2, 2 => -1, 3 => 0, 4 => -2, 5 => -1

Say you have to stay up for some reason 30 hours, how many hours will you have left of that day? 30 mod -24.

But what C implements is not mod, it's a remainder. Anyway, the point is that it does make sense to return negatives.

FelipeC
  • 9,123
  • 4
  • 44
  • 38
0

If N is the modulus (ie the divisor), then

(x + N) % N

will simply return the modulo of x.

In other words, as a function:

const modulo = (x, N) => (x + N) % N

Example:

result = modulo(-3, 12) // 9

Ellis
  • 395
  • 3
  • 8
-2

It seems the problem is that / is not floor operation.

int mod(int m, float n)
{  
  return m - floor(m/n)*n;
}
baz
  • 1,317
  • 15
  • 10