Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remainder operator in c89 and c99

Tags:

c

c99

c89

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?

like image 912
Juan Avatar asked Nov 03 '12 10:11

Juan


People also ask

What is operator for remainder?

Remainder (%) The remainder operator ( % ) returns the remainder left over when one operand is divided by a second operand.

What is remainder operator in C?

The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.

Which arithmetic operator gives remainder?

The // (remainder) operator returns the remainder from integer division and is defined as being the residue of the dividend after the operation of calculating integer division as previously described. The sign of the remainder, if nonzero, is the same as that of the original dividend.

Which operator gives remainder in C++?

Modulo Operator (%) in C/C++ with Examples The modulo division operator produces the remainder of an integer division.


2 Answers

% 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
like image 33
ouah Avatar answered Sep 20 '22 04:09

ouah


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.

like image 87
Pascal Cuoq Avatar answered Sep 18 '22 04:09

Pascal Cuoq