Question

c99 standard says that result of modulo operation has same sign as first operand. So -9 % 7 = -2 and 9 % -7 = 2.

I read in one book that c89 standard depends on implementation. So -9 % 7 could yield -2 or 5??? How remainder of -9 / 7 could be 5?

Was it helpful?

Solution

Consider two numbers a and b.

The quotient q=a/b and remainder r=a%b satisfy the equation a == q*b + r.

An (hypothetical) implementation of C89 in which -9 % 7 produces 5 is an implementation in which -9 / 7 is computed as -2.

The mathematical (Euclidian) division constrains r to be positive and smaller than b. C99 constrains it to be of the same sign as a and strictly between -b and b. It is all only a matter of convention.

OTHER TIPS

% operator is defined as:

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

so

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

% as a remainder operator

If / rounds towards 0 (like C99):

-9 % 7 == -2

you have -9 / 7 == -1 so the % is -2 because

-9 % 7 == -9 - (-9 / 7 * 7) + 9 == -9 + 7 == -2 

% as a modulo operator

If / rounds towards minus infinity:

-9 % 7 == 5

you have -9 / 7 == -2 so the % is 5

-9 % 7 == -9 - (-9 / 7 * 7) + 9 == -9 + 14 == 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top