Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C remainder/modulo operator definition for positive arguments

I found a function in a program I am supposed to fix that has a mod function defined:

int mod(int a, int b)
{
  int i = a%b;
  if(i<0) i+=b;
  return i;
}

I was told that a and b will always be positive by the way...

Huh? if(i<0)?

The argument is, that

the result of the modulo operation is an equivalence class, and any member of the class may be chosen as representative

And only as an afterthought

...; however, the usual representative is the least positive residue, the smallest nonnegative integer that belongs to that class, i.e. the remainder of the Euclidean division. However, other conventions are possible.

That means that 6 % 7 could return 6 (so far so good), but also -1. Hrm... really? (Lets ignore the fact that the presented implementation does not handle all cases.)

I know that it is mathematically true that the modulo operation is like this. But then someone else told me that the C % does in fact "not implement the modulo operator but the remainder".

So, how does C define the % operator?

In the C-Draft I only find

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.

Does this mean, that 6 % 7 is always 6? Or can it be -1, too?

like image 892
towi Avatar asked Dec 11 '22 01:12

towi


1 Answers

According to the standard:

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

This means that the sign of a is preserved in the modulo.

 17 %  3  ->  2
 17 % -3  ->  2
-17 %  3  -> -2
-17 % -3  -> -2

So no, 6%7 cannot be -1 because the reminder has to have the same sign of the dividend.

like image 111
Davide Spataro Avatar answered Dec 12 '22 14:12

Davide Spataro