3

The following is an excerpt from the C book by Mike Banahan & Brady (Link: Section 2.8.2.1). A pleb like me has no reason to doubt that the author is wrong, unless you folks suggest otherwise.

Please tell me how on earth "(a/b)*b + a%b - a" is always zero for integers where b is not zero.

Extracted text follows:

If either operand is negative, the result of / may be the nearest integer to the true result on either side, and the sign of the result of % may be positive or negative. Both of these features are implementation defined.

It is always true that the following expression is equal to zero:

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

unless b is zero.

The usual arithmetic conversions are applied to both of the operands.

Thokchom
  • 1,602
  • 3
  • 17
  • 32
  • As a note, it was implementation-defined in C89. Since C99, division is defined as rounding towards 0 (and the given equation still holds). – mafso Sep 21 '14 at 17:18

3 Answers3

4

This is true by definition of the % operator in C.

The definition of the remainder operator in the C Standard says:

(C11, 6.5.5p6) "If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a;"

Also note that for both / and %, if the second operand is 0 the Standard specifies the operation to be undefined behavior.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Hmmnn....answers it....all meat..I am trying to chew...it will take a while to digest.. +1. – Thokchom Sep 21 '14 at 15:01
  • 2
    I never expected this example could be in standard :O – haccks Sep 21 '14 at 15:21
  • @haccks Wait a minute...did I just inadvertently mention an expression from the standard in my question? :-) – Thokchom Sep 21 '14 at 15:25
  • @haccks Can you please look into what I have asked in the second update in the question http://stackoverflow.com/questions/25960878/how-possibly-can-a-unary-operator-cause-integral-promotion-in-a-or-a/25960900#25960900 – Thokchom Sep 21 '14 at 17:26
4

Mathematically...

On paper, (a/b)*b == a (b cancels) which is why the result looks funny.

However, the computer first computes (a/b), and then multiplies by b. If this is done in integer arithmetic, then a/b is potentially rounded down before the multiplication.

If a < b, then the result of a/b is 0 , and a%b is a, giving 0 + a - a == 0

if a > b, then (a/b)*b == floor(a/b) and (a/b)*b + a%b == a, again giving 0.

Essentially this is a test of whether the compiler is correctly performing integer arithmetic

Lumi
  • 186
  • 1
  • 8
2

If num1/num2 gives quotient q and remainder r,
then num1 = q*num2 + r

Here taking num1 as a and num2 as b, then a/b is the quotient part and remainder part is a%b.

So a=(a/b)*b+(a%b) and (a/b)*b+(a%b)-a is equal to 0

Pratyush Khare
  • 689
  • 5
  • 16